1 /*
   2  * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #ifndef _WINDOWS
  27 #include "alloca.h"
  28 #endif
  29 #include "asm/macroAssembler.hpp"
  30 #include "asm/macroAssembler.inline.hpp"
  31 #include "code/debugInfoRec.hpp"
  32 #include "code/icBuffer.hpp"
  33 #include "code/vtableStubs.hpp"
  34 #include "interpreter/interpreter.hpp"
  35 #include "oops/compiledICHolder.hpp"
  36 #include "prims/jvmtiRedefineClassesTrace.hpp"
  37 #include "runtime/sharedRuntime.hpp"
  38 #include "runtime/vframeArray.hpp"
  39 #include "vmreg_x86.inline.hpp"
  40 #ifdef COMPILER1
  41 #include "c1/c1_Runtime1.hpp"
  42 #endif
  43 #ifdef COMPILER2
  44 #include "opto/runtime.hpp"
  45 #endif
  46 #if INCLUDE_JVMCI
  47 #include "jvmci/jvmciJavaClasses.hpp"
  48 #endif
  49 
  50 #define __ masm->
  51 
  52 const int StackAlignmentInSlots = StackAlignmentInBytes / VMRegImpl::stack_slot_size;
  53 
  54 class SimpleRuntimeFrame {
  55 
  56   public:
  57 
  58   // Most of the runtime stubs have this simple frame layout.
  59   // This class exists to make the layout shared in one place.
  60   // Offsets are for compiler stack slots, which are jints.
  61   enum layout {
  62     // The frame sender code expects that rbp will be in the "natural" place and
  63     // will override any oopMap setting for it. We must therefore force the layout
  64     // so that it agrees with the frame sender code.
  65     rbp_off = frame::arg_reg_save_area_bytes/BytesPerInt,
  66     rbp_off2,
  67     return_off, return_off2,
  68     framesize
  69   };
  70 };
  71 
  72 class RegisterSaver {
  73   // Capture info about frame layout.  Layout offsets are in jint
  74   // units because compiler frame slots are jints.
  75 #define XSAVE_AREA_BEGIN 160
  76 #define XSAVE_AREA_YMM_BEGIN 576
  77 #define XSAVE_AREA_ZMM_BEGIN 1152
  78 #define XSAVE_AREA_UPPERBANK 1664
  79 #define DEF_XMM_OFFS(regnum) xmm ## regnum ## _off = xmm_off + (regnum)*16/BytesPerInt, xmm ## regnum ## H_off
  80 #define DEF_YMM_OFFS(regnum) ymm ## regnum ## _off = ymm_off + (regnum)*16/BytesPerInt, ymm ## regnum ## H_off
  81 #define DEF_ZMM_OFFS(regnum) zmm ## regnum ## _off = zmm_off + (regnum-16)*64/BytesPerInt, zmm ## regnum ## H_off
  82   enum layout {
  83     fpu_state_off = frame::arg_reg_save_area_bytes/BytesPerInt, // fxsave save area
  84     xmm_off       = fpu_state_off + XSAVE_AREA_BEGIN/BytesPerInt,            // offset in fxsave save area
  85     DEF_XMM_OFFS(0),
  86     DEF_XMM_OFFS(1),
  87     // 2..15 are implied in range usage
  88     ymm_off = xmm_off + (XSAVE_AREA_YMM_BEGIN - XSAVE_AREA_BEGIN)/BytesPerInt,
  89     DEF_YMM_OFFS(0),
  90     DEF_YMM_OFFS(1),
  91     // 2..15 are implied in range usage
  92     zmm_high = xmm_off + (XSAVE_AREA_ZMM_BEGIN - XSAVE_AREA_BEGIN)/BytesPerInt,
  93     zmm_off = xmm_off + (XSAVE_AREA_UPPERBANK - XSAVE_AREA_BEGIN)/BytesPerInt,
  94     DEF_ZMM_OFFS(16),
  95     DEF_ZMM_OFFS(17),
  96     // 18..31 are implied in range usage
  97     fpu_state_end = fpu_state_off + ((FPUStateSizeInWords-1)*wordSize / BytesPerInt),
  98     fpu_stateH_end,
  99     r15_off, r15H_off,
 100     r14_off, r14H_off,
 101     r13_off, r13H_off,
 102     r12_off, r12H_off,
 103     r11_off, r11H_off,
 104     r10_off, r10H_off,
 105     r9_off,  r9H_off,
 106     r8_off,  r8H_off,
 107     rdi_off, rdiH_off,
 108     rsi_off, rsiH_off,
 109     ignore_off, ignoreH_off,  // extra copy of rbp
 110     rsp_off, rspH_off,
 111     rbx_off, rbxH_off,
 112     rdx_off, rdxH_off,
 113     rcx_off, rcxH_off,
 114     rax_off, raxH_off,
 115     // 16-byte stack alignment fill word: see MacroAssembler::push/pop_IU_state
 116     align_off, alignH_off,
 117     flags_off, flagsH_off,
 118     // The frame sender code expects that rbp will be in the "natural" place and
 119     // will override any oopMap setting for it. We must therefore force the layout
 120     // so that it agrees with the frame sender code.
 121     rbp_off, rbpH_off,        // copy of rbp we will restore
 122     return_off, returnH_off,  // slot for return address
 123     reg_save_size             // size in compiler stack slots
 124   };
 125 
 126  public:
 127   static OopMap* save_live_registers(MacroAssembler* masm, int additional_frame_words, int* total_frame_words, bool save_vectors = false);
 128   static void restore_live_registers(MacroAssembler* masm, bool restore_vectors = false);
 129 
 130   // Offsets into the register save area
 131   // Used by deoptimization when it is managing result register
 132   // values on its own
 133 
 134   static int rax_offset_in_bytes(void)    { return BytesPerInt * rax_off; }
 135   static int rdx_offset_in_bytes(void)    { return BytesPerInt * rdx_off; }
 136   static int rbx_offset_in_bytes(void)    { return BytesPerInt * rbx_off; }
 137   static int xmm0_offset_in_bytes(void)   { return BytesPerInt * xmm0_off; }
 138   static int return_offset_in_bytes(void) { return BytesPerInt * return_off; }
 139 
 140   // During deoptimization only the result registers need to be restored,
 141   // all the other values have already been extracted.
 142   static void restore_result_registers(MacroAssembler* masm);
 143 };
 144 
 145 OopMap* RegisterSaver::save_live_registers(MacroAssembler* masm, int additional_frame_words, int* total_frame_words, bool save_vectors) {
 146   int off = 0;
 147   int num_xmm_regs = XMMRegisterImpl::number_of_registers;
 148   if (UseAVX < 3) {
 149     num_xmm_regs = num_xmm_regs/2;
 150   }
 151 #if defined(COMPILER2) || INCLUDE_JVMCI
 152   if (save_vectors) {
 153     assert(UseAVX > 0, "512bit vectors are supported only with EVEX");
 154     assert(MaxVectorSize == 64, "only 512bit vectors are supported now");
 155   }
 156 #else
 157   assert(!save_vectors, "vectors are generated only by C2 and JVMCI");
 158 #endif
 159 
 160   // Always make the frame size 16-byte aligned, both vector and non vector stacks are always allocated
 161   int frame_size_in_bytes = round_to(reg_save_size*BytesPerInt, num_xmm_regs);
 162   // OopMap frame size is in compiler stack slots (jint's) not bytes or words
 163   int frame_size_in_slots = frame_size_in_bytes / BytesPerInt;
 164   // CodeBlob frame size is in words.
 165   int frame_size_in_words = frame_size_in_bytes / wordSize;
 166   *total_frame_words = frame_size_in_words;
 167 
 168   // Save registers, fpu state, and flags.
 169   // We assume caller has already pushed the return address onto the
 170   // stack, so rsp is 8-byte aligned here.
 171   // We push rpb twice in this sequence because we want the real rbp
 172   // to be under the return like a normal enter.
 173 
 174   __ enter();          // rsp becomes 16-byte aligned here
 175   __ push_CPU_state(); // Push a multiple of 16 bytes
 176 
 177   // push cpu state handles this on EVEX enabled targets
 178   if (save_vectors) {
 179     // Save upper half of YMM registes(0..15)
 180     int base_addr = XSAVE_AREA_YMM_BEGIN;
 181     for (int n = 0; n < 16; n++) {
 182       __ vextractf128h(Address(rsp, base_addr+n*16), as_XMMRegister(n));
 183     }
 184     if (VM_Version::supports_evex()) {
 185       // Save upper half of ZMM registes(0..15)
 186       base_addr = XSAVE_AREA_ZMM_BEGIN;
 187       for (int n = 0; n < 16; n++) {
 188         __ vextractf64x4h(Address(rsp, base_addr+n*32), as_XMMRegister(n), 1);
 189       }
 190       // Save full ZMM registes(16..num_xmm_regs)
 191       base_addr = XSAVE_AREA_UPPERBANK;
 192       off = 0;
 193       int vector_len = Assembler::AVX_512bit;
 194       for (int n = 16; n < num_xmm_regs; n++) {
 195         __ evmovdqul(Address(rsp, base_addr+(off++*64)), as_XMMRegister(n), vector_len);
 196       }
 197     }
 198   } else {
 199     if (VM_Version::supports_evex()) {
 200       // Save upper bank of ZMM registers(16..31) for double/float usage
 201       int base_addr = XSAVE_AREA_UPPERBANK;
 202       off = 0;
 203       for (int n = 16; n < num_xmm_regs; n++) {
 204         __ movsd(Address(rsp, base_addr+(off++*64)), as_XMMRegister(n));
 205       }
 206     }
 207   }
 208   if (frame::arg_reg_save_area_bytes != 0) {
 209     // Allocate argument register save area
 210     __ subptr(rsp, frame::arg_reg_save_area_bytes);
 211   }
 212 
 213   // Set an oopmap for the call site.  This oopmap will map all
 214   // oop-registers and debug-info registers as callee-saved.  This
 215   // will allow deoptimization at this safepoint to find all possible
 216   // debug-info recordings, as well as let GC find all oops.
 217 
 218   OopMapSet *oop_maps = new OopMapSet();
 219   OopMap* map = new OopMap(frame_size_in_slots, 0);
 220 
 221 #define STACK_OFFSET(x) VMRegImpl::stack2reg((x))
 222 
 223   map->set_callee_saved(STACK_OFFSET( rax_off ), rax->as_VMReg());
 224   map->set_callee_saved(STACK_OFFSET( rcx_off ), rcx->as_VMReg());
 225   map->set_callee_saved(STACK_OFFSET( rdx_off ), rdx->as_VMReg());
 226   map->set_callee_saved(STACK_OFFSET( rbx_off ), rbx->as_VMReg());
 227   // rbp location is known implicitly by the frame sender code, needs no oopmap
 228   // and the location where rbp was saved by is ignored
 229   map->set_callee_saved(STACK_OFFSET( rsi_off ), rsi->as_VMReg());
 230   map->set_callee_saved(STACK_OFFSET( rdi_off ), rdi->as_VMReg());
 231   map->set_callee_saved(STACK_OFFSET( r8_off  ), r8->as_VMReg());
 232   map->set_callee_saved(STACK_OFFSET( r9_off  ), r9->as_VMReg());
 233   map->set_callee_saved(STACK_OFFSET( r10_off ), r10->as_VMReg());
 234   map->set_callee_saved(STACK_OFFSET( r11_off ), r11->as_VMReg());
 235   map->set_callee_saved(STACK_OFFSET( r12_off ), r12->as_VMReg());
 236   map->set_callee_saved(STACK_OFFSET( r13_off ), r13->as_VMReg());
 237   map->set_callee_saved(STACK_OFFSET( r14_off ), r14->as_VMReg());
 238   map->set_callee_saved(STACK_OFFSET( r15_off ), r15->as_VMReg());
 239   // For both AVX and EVEX we will use the legacy FXSAVE area for xmm0..xmm15,
 240   // on EVEX enabled targets, we get it included in the xsave area
 241   off = xmm0_off;
 242   int delta = xmm1_off - off;
 243   for (int n = 0; n < 16; n++) {
 244     XMMRegister xmm_name = as_XMMRegister(n);
 245     map->set_callee_saved(STACK_OFFSET(off), xmm_name->as_VMReg());
 246     off += delta;
 247   }
 248   if(UseAVX > 2) {
 249     // Obtain xmm16..xmm31 from the XSAVE area on EVEX enabled targets
 250     off = zmm16_off;
 251     delta = zmm17_off - off;
 252     for (int n = 16; n < num_xmm_regs; n++) {
 253       XMMRegister zmm_name = as_XMMRegister(n);
 254       map->set_callee_saved(STACK_OFFSET(off), zmm_name->as_VMReg());
 255       off += delta;
 256     }
 257   }
 258 
 259 #if defined(COMPILER2) || INCLUDE_JVMCI
 260   if (save_vectors) {
 261     off = ymm0_off;
 262     int delta = ymm1_off - off;
 263     for (int n = 0; n < 16; n++) {
 264       XMMRegister ymm_name = as_XMMRegister(n);
 265       map->set_callee_saved(STACK_OFFSET(off), ymm_name->as_VMReg()->next(4));
 266       off += delta;
 267     }
 268   }
 269 #endif // COMPILER2 || INCLUDE_JVMCI
 270 
 271   // %%% These should all be a waste but we'll keep things as they were for now
 272   if (true) {
 273     map->set_callee_saved(STACK_OFFSET( raxH_off ), rax->as_VMReg()->next());
 274     map->set_callee_saved(STACK_OFFSET( rcxH_off ), rcx->as_VMReg()->next());
 275     map->set_callee_saved(STACK_OFFSET( rdxH_off ), rdx->as_VMReg()->next());
 276     map->set_callee_saved(STACK_OFFSET( rbxH_off ), rbx->as_VMReg()->next());
 277     // rbp location is known implicitly by the frame sender code, needs no oopmap
 278     map->set_callee_saved(STACK_OFFSET( rsiH_off ), rsi->as_VMReg()->next());
 279     map->set_callee_saved(STACK_OFFSET( rdiH_off ), rdi->as_VMReg()->next());
 280     map->set_callee_saved(STACK_OFFSET( r8H_off  ), r8->as_VMReg()->next());
 281     map->set_callee_saved(STACK_OFFSET( r9H_off  ), r9->as_VMReg()->next());
 282     map->set_callee_saved(STACK_OFFSET( r10H_off ), r10->as_VMReg()->next());
 283     map->set_callee_saved(STACK_OFFSET( r11H_off ), r11->as_VMReg()->next());
 284     map->set_callee_saved(STACK_OFFSET( r12H_off ), r12->as_VMReg()->next());
 285     map->set_callee_saved(STACK_OFFSET( r13H_off ), r13->as_VMReg()->next());
 286     map->set_callee_saved(STACK_OFFSET( r14H_off ), r14->as_VMReg()->next());
 287     map->set_callee_saved(STACK_OFFSET( r15H_off ), r15->as_VMReg()->next());
 288     // For both AVX and EVEX we will use the legacy FXSAVE area for xmm0..xmm15,
 289     // on EVEX enabled targets, we get it included in the xsave area
 290     off = xmm0H_off;
 291     delta = xmm1H_off - off;
 292     for (int n = 0; n < 16; n++) {
 293       XMMRegister xmm_name = as_XMMRegister(n);
 294       map->set_callee_saved(STACK_OFFSET(off), xmm_name->as_VMReg()->next());
 295       off += delta;
 296     }
 297     if (UseAVX > 2) {
 298       // Obtain xmm16..xmm31 from the XSAVE area on EVEX enabled targets
 299       off = zmm16H_off;
 300       delta = zmm17H_off - off;
 301       for (int n = 16; n < num_xmm_regs; n++) {
 302         XMMRegister zmm_name = as_XMMRegister(n);
 303         map->set_callee_saved(STACK_OFFSET(off), zmm_name->as_VMReg()->next());
 304         off += delta;
 305       }
 306     }
 307   }
 308 
 309   return map;
 310 }
 311 
 312 void RegisterSaver::restore_live_registers(MacroAssembler* masm, bool restore_vectors) {
 313   int num_xmm_regs = XMMRegisterImpl::number_of_registers;
 314   if (UseAVX < 3) {
 315     num_xmm_regs = num_xmm_regs/2;
 316   }
 317   if (frame::arg_reg_save_area_bytes != 0) {
 318     // Pop arg register save area
 319     __ addptr(rsp, frame::arg_reg_save_area_bytes);
 320   }
 321 
 322 #if defined(COMPILER2) || INCLUDE_JVMCI
 323   if (restore_vectors) {
 324     assert(UseAVX > 0, "512bit vectors are supported only with EVEX");
 325     assert(MaxVectorSize == 64, "only 512bit vectors are supported now");
 326   }
 327 #else
 328   assert(!restore_vectors, "vectors are generated only by C2");
 329 #endif
 330 
 331   // On EVEX enabled targets everything is handled in pop fpu state
 332   if (restore_vectors) {
 333     // Restore upper half of YMM registes (0..15)
 334     int base_addr = XSAVE_AREA_YMM_BEGIN;
 335     for (int n = 0; n < 16; n++) {
 336       __ vinsertf128h(as_XMMRegister(n), Address(rsp,  base_addr+n*16));
 337     }
 338     if (VM_Version::supports_evex()) {
 339       // Restore upper half of ZMM registes (0..15)
 340       base_addr = XSAVE_AREA_ZMM_BEGIN;
 341       for (int n = 0; n < 16; n++) {
 342         __ vinsertf64x4h(as_XMMRegister(n), Address(rsp, base_addr+n*32), 1);
 343       }
 344       // Restore full ZMM registes(16..num_xmm_regs)
 345       base_addr = XSAVE_AREA_UPPERBANK;
 346       int vector_len = Assembler::AVX_512bit;
 347       int off = 0;
 348       for (int n = 16; n < num_xmm_regs; n++) {
 349         __ evmovdqul(as_XMMRegister(n), Address(rsp, base_addr+(off++*64)), vector_len);
 350       }
 351     }
 352   } else {
 353     if (VM_Version::supports_evex()) {
 354       // Restore upper bank of ZMM registes(16..31) for double/float usage
 355       int base_addr = XSAVE_AREA_UPPERBANK;
 356       int off = 0;
 357       for (int n = 16; n < num_xmm_regs; n++) {
 358         __ movsd(as_XMMRegister(n), Address(rsp, base_addr+(off++*64)));
 359       }
 360     }
 361   }
 362 
 363   // Recover CPU state
 364   __ pop_CPU_state();
 365   // Get the rbp described implicitly by the calling convention (no oopMap)
 366   __ pop(rbp);
 367 }
 368 
 369 void RegisterSaver::restore_result_registers(MacroAssembler* masm) {
 370 
 371   // Just restore result register. Only used by deoptimization. By
 372   // now any callee save register that needs to be restored to a c2
 373   // caller of the deoptee has been extracted into the vframeArray
 374   // and will be stuffed into the c2i adapter we create for later
 375   // restoration so only result registers need to be restored here.
 376 
 377   // Restore fp result register
 378   __ movdbl(xmm0, Address(rsp, xmm0_offset_in_bytes()));
 379   // Restore integer result register
 380   __ movptr(rax, Address(rsp, rax_offset_in_bytes()));
 381   __ movptr(rdx, Address(rsp, rdx_offset_in_bytes()));
 382 
 383   // Pop all of the register save are off the stack except the return address
 384   __ addptr(rsp, return_offset_in_bytes());
 385 }
 386 
 387 // Is vector's size (in bytes) bigger than a size saved by default?
 388 // 16 bytes XMM registers are saved by default using fxsave/fxrstor instructions.
 389 bool SharedRuntime::is_wide_vector(int size) {
 390   return size > 16;
 391 }
 392 
 393 size_t SharedRuntime::trampoline_size() {
 394   return 16;
 395 }
 396 
 397 void SharedRuntime::generate_trampoline(MacroAssembler *masm, address destination) {
 398   __ jump(RuntimeAddress(destination));
 399 }
 400 
 401 // The java_calling_convention describes stack locations as ideal slots on
 402 // a frame with no abi restrictions. Since we must observe abi restrictions
 403 // (like the placement of the register window) the slots must be biased by
 404 // the following value.
 405 static int reg2offset_in(VMReg r) {
 406   // Account for saved rbp and return address
 407   // This should really be in_preserve_stack_slots
 408   return (r->reg2stack() + 4) * VMRegImpl::stack_slot_size;
 409 }
 410 
 411 static int reg2offset_out(VMReg r) {
 412   return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
 413 }
 414 
 415 // ---------------------------------------------------------------------------
 416 // Read the array of BasicTypes from a signature, and compute where the
 417 // arguments should go.  Values in the VMRegPair regs array refer to 4-byte
 418 // quantities.  Values less than VMRegImpl::stack0 are registers, those above
 419 // refer to 4-byte stack slots.  All stack slots are based off of the stack pointer
 420 // as framesizes are fixed.
 421 // VMRegImpl::stack0 refers to the first slot 0(sp).
 422 // and VMRegImpl::stack0+1 refers to the memory word 4-byes higher.  Register
 423 // up to RegisterImpl::number_of_registers) are the 64-bit
 424 // integer registers.
 425 
 426 // Note: the INPUTS in sig_bt are in units of Java argument words, which are
 427 // either 32-bit or 64-bit depending on the build.  The OUTPUTS are in 32-bit
 428 // units regardless of build. Of course for i486 there is no 64 bit build
 429 
 430 // The Java calling convention is a "shifted" version of the C ABI.
 431 // By skipping the first C ABI register we can call non-static jni methods
 432 // with small numbers of arguments without having to shuffle the arguments
 433 // at all. Since we control the java ABI we ought to at least get some
 434 // advantage out of it.
 435 
 436 int SharedRuntime::java_calling_convention(const BasicType *sig_bt,
 437                                            VMRegPair *regs,
 438                                            int total_args_passed,
 439                                            int is_outgoing) {
 440 
 441   // Create the mapping between argument positions and
 442   // registers.
 443   static const Register INT_ArgReg[Argument::n_int_register_parameters_j] = {
 444     j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5
 445   };
 446   static const XMMRegister FP_ArgReg[Argument::n_float_register_parameters_j] = {
 447     j_farg0, j_farg1, j_farg2, j_farg3,
 448     j_farg4, j_farg5, j_farg6, j_farg7
 449   };
 450 
 451 
 452   uint int_args = 0;
 453   uint fp_args = 0;
 454   uint stk_args = 0; // inc by 2 each time
 455 
 456   for (int i = 0; i < total_args_passed; i++) {
 457     switch (sig_bt[i]) {
 458     case T_BOOLEAN:
 459     case T_CHAR:
 460     case T_BYTE:
 461     case T_SHORT:
 462     case T_INT:
 463       if (int_args < Argument::n_int_register_parameters_j) {
 464         regs[i].set1(INT_ArgReg[int_args++]->as_VMReg());
 465       } else {
 466         regs[i].set1(VMRegImpl::stack2reg(stk_args));
 467         stk_args += 2;
 468       }
 469       break;
 470     case T_VOID:
 471       // halves of T_LONG or T_DOUBLE
 472       assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
 473       regs[i].set_bad();
 474       break;
 475     case T_LONG:
 476       assert(sig_bt[i + 1] == T_VOID, "expecting half");
 477       // fall through
 478     case T_OBJECT:
 479     case T_ARRAY:
 480     case T_ADDRESS:
 481       if (int_args < Argument::n_int_register_parameters_j) {
 482         regs[i].set2(INT_ArgReg[int_args++]->as_VMReg());
 483       } else {
 484         regs[i].set2(VMRegImpl::stack2reg(stk_args));
 485         stk_args += 2;
 486       }
 487       break;
 488     case T_FLOAT:
 489       if (fp_args < Argument::n_float_register_parameters_j) {
 490         regs[i].set1(FP_ArgReg[fp_args++]->as_VMReg());
 491       } else {
 492         regs[i].set1(VMRegImpl::stack2reg(stk_args));
 493         stk_args += 2;
 494       }
 495       break;
 496     case T_DOUBLE:
 497       assert(sig_bt[i + 1] == T_VOID, "expecting half");
 498       if (fp_args < Argument::n_float_register_parameters_j) {
 499         regs[i].set2(FP_ArgReg[fp_args++]->as_VMReg());
 500       } else {
 501         regs[i].set2(VMRegImpl::stack2reg(stk_args));
 502         stk_args += 2;
 503       }
 504       break;
 505     default:
 506       ShouldNotReachHere();
 507       break;
 508     }
 509   }
 510 
 511   return round_to(stk_args, 2);
 512 }
 513 
 514 // Patch the callers callsite with entry to compiled code if it exists.
 515 static void patch_callers_callsite(MacroAssembler *masm) {
 516   Label L;
 517   __ cmpptr(Address(rbx, in_bytes(Method::code_offset())), (int32_t)NULL_WORD);
 518   __ jcc(Assembler::equal, L);
 519 
 520   // Save the current stack pointer
 521   __ mov(r13, rsp);
 522   // Schedule the branch target address early.
 523   // Call into the VM to patch the caller, then jump to compiled callee
 524   // rax isn't live so capture return address while we easily can
 525   __ movptr(rax, Address(rsp, 0));
 526 
 527   // align stack so push_CPU_state doesn't fault
 528   __ andptr(rsp, -(StackAlignmentInBytes));
 529   __ push_CPU_state();
 530 
 531   // VM needs caller's callsite
 532   // VM needs target method
 533   // This needs to be a long call since we will relocate this adapter to
 534   // the codeBuffer and it may not reach
 535 
 536   // Allocate argument register save area
 537   if (frame::arg_reg_save_area_bytes != 0) {
 538     __ subptr(rsp, frame::arg_reg_save_area_bytes);
 539   }
 540   __ mov(c_rarg0, rbx);
 541   __ mov(c_rarg1, rax);
 542   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::fixup_callers_callsite)));
 543 
 544   // De-allocate argument register save area
 545   if (frame::arg_reg_save_area_bytes != 0) {
 546     __ addptr(rsp, frame::arg_reg_save_area_bytes);
 547   }
 548 
 549   __ pop_CPU_state();
 550   // restore sp
 551   __ mov(rsp, r13);
 552   __ bind(L);
 553 }
 554 
 555 
 556 static void gen_c2i_adapter(MacroAssembler *masm,
 557                             int total_args_passed,
 558                             int comp_args_on_stack,
 559                             const BasicType *sig_bt,
 560                             const VMRegPair *regs,
 561                             Label& skip_fixup) {
 562   // Before we get into the guts of the C2I adapter, see if we should be here
 563   // at all.  We've come from compiled code and are attempting to jump to the
 564   // interpreter, which means the caller made a static call to get here
 565   // (vcalls always get a compiled target if there is one).  Check for a
 566   // compiled target.  If there is one, we need to patch the caller's call.
 567   patch_callers_callsite(masm);
 568 
 569   __ bind(skip_fixup);
 570 
 571   // Since all args are passed on the stack, total_args_passed *
 572   // Interpreter::stackElementSize is the space we need. Plus 1 because
 573   // we also account for the return address location since
 574   // we store it first rather than hold it in rax across all the shuffling
 575 
 576   int extraspace = (total_args_passed * Interpreter::stackElementSize) + wordSize;
 577 
 578   // stack is aligned, keep it that way
 579   extraspace = round_to(extraspace, 2*wordSize);
 580 
 581   // Get return address
 582   __ pop(rax);
 583 
 584   // set senderSP value
 585   __ mov(r13, rsp);
 586 
 587   __ subptr(rsp, extraspace);
 588 
 589   // Store the return address in the expected location
 590   __ movptr(Address(rsp, 0), rax);
 591 
 592   // Now write the args into the outgoing interpreter space
 593   for (int i = 0; i < total_args_passed; i++) {
 594     if (sig_bt[i] == T_VOID) {
 595       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
 596       continue;
 597     }
 598 
 599     // offset to start parameters
 600     int st_off   = (total_args_passed - i) * Interpreter::stackElementSize;
 601     int next_off = st_off - Interpreter::stackElementSize;
 602 
 603     // Say 4 args:
 604     // i   st_off
 605     // 0   32 T_LONG
 606     // 1   24 T_VOID
 607     // 2   16 T_OBJECT
 608     // 3    8 T_BOOL
 609     // -    0 return address
 610     //
 611     // However to make thing extra confusing. Because we can fit a long/double in
 612     // a single slot on a 64 bt vm and it would be silly to break them up, the interpreter
 613     // leaves one slot empty and only stores to a single slot. In this case the
 614     // slot that is occupied is the T_VOID slot. See I said it was confusing.
 615 
 616     VMReg r_1 = regs[i].first();
 617     VMReg r_2 = regs[i].second();
 618     if (!r_1->is_valid()) {
 619       assert(!r_2->is_valid(), "");
 620       continue;
 621     }
 622     if (r_1->is_stack()) {
 623       // memory to memory use rax
 624       int ld_off = r_1->reg2stack() * VMRegImpl::stack_slot_size + extraspace;
 625       if (!r_2->is_valid()) {
 626         // sign extend??
 627         __ movl(rax, Address(rsp, ld_off));
 628         __ movptr(Address(rsp, st_off), rax);
 629 
 630       } else {
 631 
 632         __ movq(rax, Address(rsp, ld_off));
 633 
 634         // Two VMREgs|OptoRegs can be T_OBJECT, T_ADDRESS, T_DOUBLE, T_LONG
 635         // T_DOUBLE and T_LONG use two slots in the interpreter
 636         if ( sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
 637           // ld_off == LSW, ld_off+wordSize == MSW
 638           // st_off == MSW, next_off == LSW
 639           __ movq(Address(rsp, next_off), rax);
 640 #ifdef ASSERT
 641           // Overwrite the unused slot with known junk
 642           __ mov64(rax, CONST64(0xdeadffffdeadaaaa));
 643           __ movptr(Address(rsp, st_off), rax);
 644 #endif /* ASSERT */
 645         } else {
 646           __ movq(Address(rsp, st_off), rax);
 647         }
 648       }
 649     } else if (r_1->is_Register()) {
 650       Register r = r_1->as_Register();
 651       if (!r_2->is_valid()) {
 652         // must be only an int (or less ) so move only 32bits to slot
 653         // why not sign extend??
 654         __ movl(Address(rsp, st_off), r);
 655       } else {
 656         // Two VMREgs|OptoRegs can be T_OBJECT, T_ADDRESS, T_DOUBLE, T_LONG
 657         // T_DOUBLE and T_LONG use two slots in the interpreter
 658         if ( sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
 659           // long/double in gpr
 660 #ifdef ASSERT
 661           // Overwrite the unused slot with known junk
 662           __ mov64(rax, CONST64(0xdeadffffdeadaaab));
 663           __ movptr(Address(rsp, st_off), rax);
 664 #endif /* ASSERT */
 665           __ movq(Address(rsp, next_off), r);
 666         } else {
 667           __ movptr(Address(rsp, st_off), r);
 668         }
 669       }
 670     } else {
 671       assert(r_1->is_XMMRegister(), "");
 672       if (!r_2->is_valid()) {
 673         // only a float use just part of the slot
 674         __ movflt(Address(rsp, st_off), r_1->as_XMMRegister());
 675       } else {
 676 #ifdef ASSERT
 677         // Overwrite the unused slot with known junk
 678         __ mov64(rax, CONST64(0xdeadffffdeadaaac));
 679         __ movptr(Address(rsp, st_off), rax);
 680 #endif /* ASSERT */
 681         __ movdbl(Address(rsp, next_off), r_1->as_XMMRegister());
 682       }
 683     }
 684   }
 685 
 686   // Schedule the branch target address early.
 687   __ movptr(rcx, Address(rbx, in_bytes(Method::interpreter_entry_offset())));
 688   __ jmp(rcx);
 689 }
 690 
 691 static void range_check(MacroAssembler* masm, Register pc_reg, Register temp_reg,
 692                         address code_start, address code_end,
 693                         Label& L_ok) {
 694   Label L_fail;
 695   __ lea(temp_reg, ExternalAddress(code_start));
 696   __ cmpptr(pc_reg, temp_reg);
 697   __ jcc(Assembler::belowEqual, L_fail);
 698   __ lea(temp_reg, ExternalAddress(code_end));
 699   __ cmpptr(pc_reg, temp_reg);
 700   __ jcc(Assembler::below, L_ok);
 701   __ bind(L_fail);
 702 }
 703 
 704 void SharedRuntime::gen_i2c_adapter(MacroAssembler *masm,
 705                                     int total_args_passed,
 706                                     int comp_args_on_stack,
 707                                     const BasicType *sig_bt,
 708                                     const VMRegPair *regs) {
 709 
 710   // Note: r13 contains the senderSP on entry. We must preserve it since
 711   // we may do a i2c -> c2i transition if we lose a race where compiled
 712   // code goes non-entrant while we get args ready.
 713   // In addition we use r13 to locate all the interpreter args as
 714   // we must align the stack to 16 bytes on an i2c entry else we
 715   // lose alignment we expect in all compiled code and register
 716   // save code can segv when fxsave instructions find improperly
 717   // aligned stack pointer.
 718 
 719   // Adapters can be frameless because they do not require the caller
 720   // to perform additional cleanup work, such as correcting the stack pointer.
 721   // An i2c adapter is frameless because the *caller* frame, which is interpreted,
 722   // routinely repairs its own stack pointer (from interpreter_frame_last_sp),
 723   // even if a callee has modified the stack pointer.
 724   // A c2i adapter is frameless because the *callee* frame, which is interpreted,
 725   // routinely repairs its caller's stack pointer (from sender_sp, which is set
 726   // up via the senderSP register).
 727   // In other words, if *either* the caller or callee is interpreted, we can
 728   // get the stack pointer repaired after a call.
 729   // This is why c2i and i2c adapters cannot be indefinitely composed.
 730   // In particular, if a c2i adapter were to somehow call an i2c adapter,
 731   // both caller and callee would be compiled methods, and neither would
 732   // clean up the stack pointer changes performed by the two adapters.
 733   // If this happens, control eventually transfers back to the compiled
 734   // caller, but with an uncorrected stack, causing delayed havoc.
 735 
 736   // Pick up the return address
 737   __ movptr(rax, Address(rsp, 0));
 738 
 739   if (VerifyAdapterCalls &&
 740       (Interpreter::code() != NULL || StubRoutines::code1() != NULL)) {
 741     // So, let's test for cascading c2i/i2c adapters right now.
 742     //  assert(Interpreter::contains($return_addr) ||
 743     //         StubRoutines::contains($return_addr),
 744     //         "i2c adapter must return to an interpreter frame");
 745     __ block_comment("verify_i2c { ");
 746     Label L_ok;
 747     if (Interpreter::code() != NULL)
 748       range_check(masm, rax, r11,
 749                   Interpreter::code()->code_start(), Interpreter::code()->code_end(),
 750                   L_ok);
 751     if (StubRoutines::code1() != NULL)
 752       range_check(masm, rax, r11,
 753                   StubRoutines::code1()->code_begin(), StubRoutines::code1()->code_end(),
 754                   L_ok);
 755     if (StubRoutines::code2() != NULL)
 756       range_check(masm, rax, r11,
 757                   StubRoutines::code2()->code_begin(), StubRoutines::code2()->code_end(),
 758                   L_ok);
 759     const char* msg = "i2c adapter must return to an interpreter frame";
 760     __ block_comment(msg);
 761     __ stop(msg);
 762     __ bind(L_ok);
 763     __ block_comment("} verify_i2ce ");
 764   }
 765 
 766   // Must preserve original SP for loading incoming arguments because
 767   // we need to align the outgoing SP for compiled code.
 768   __ movptr(r11, rsp);
 769 
 770   // Cut-out for having no stack args.  Since up to 2 int/oop args are passed
 771   // in registers, we will occasionally have no stack args.
 772   int comp_words_on_stack = 0;
 773   if (comp_args_on_stack) {
 774     // Sig words on the stack are greater-than VMRegImpl::stack0.  Those in
 775     // registers are below.  By subtracting stack0, we either get a negative
 776     // number (all values in registers) or the maximum stack slot accessed.
 777 
 778     // Convert 4-byte c2 stack slots to words.
 779     comp_words_on_stack = round_to(comp_args_on_stack*VMRegImpl::stack_slot_size, wordSize)>>LogBytesPerWord;
 780     // Round up to miminum stack alignment, in wordSize
 781     comp_words_on_stack = round_to(comp_words_on_stack, 2);
 782     __ subptr(rsp, comp_words_on_stack * wordSize);
 783   }
 784 
 785 
 786   // Ensure compiled code always sees stack at proper alignment
 787   __ andptr(rsp, -16);
 788 
 789   // push the return address and misalign the stack that youngest frame always sees
 790   // as far as the placement of the call instruction
 791   __ push(rax);
 792 
 793   // Put saved SP in another register
 794   const Register saved_sp = rax;
 795   __ movptr(saved_sp, r11);
 796 
 797   // Will jump to the compiled code just as if compiled code was doing it.
 798   // Pre-load the register-jump target early, to schedule it better.
 799   __ movptr(r11, Address(rbx, in_bytes(Method::from_compiled_offset())));
 800 
 801 #if INCLUDE_JVMCI
 802   if (EnableJVMCI) {
 803     // check if this call should be routed towards a specific entry point
 804     __ cmpptr(Address(r15_thread, in_bytes(JavaThread::jvmci_alternate_call_target_offset())), 0);
 805     Label no_alternative_target;
 806     __ jcc(Assembler::equal, no_alternative_target);
 807     __ movptr(r11, Address(r15_thread, in_bytes(JavaThread::jvmci_alternate_call_target_offset())));
 808     __ movptr(Address(r15_thread, in_bytes(JavaThread::jvmci_alternate_call_target_offset())), 0);
 809     __ bind(no_alternative_target);
 810   }
 811 #endif // INCLUDE_JVMCI
 812 
 813   // Now generate the shuffle code.  Pick up all register args and move the
 814   // rest through the floating point stack top.
 815   for (int i = 0; i < total_args_passed; i++) {
 816     if (sig_bt[i] == T_VOID) {
 817       // Longs and doubles are passed in native word order, but misaligned
 818       // in the 32-bit build.
 819       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
 820       continue;
 821     }
 822 
 823     // Pick up 0, 1 or 2 words from SP+offset.
 824 
 825     assert(!regs[i].second()->is_valid() || regs[i].first()->next() == regs[i].second(),
 826             "scrambled load targets?");
 827     // Load in argument order going down.
 828     int ld_off = (total_args_passed - i)*Interpreter::stackElementSize;
 829     // Point to interpreter value (vs. tag)
 830     int next_off = ld_off - Interpreter::stackElementSize;
 831     //
 832     //
 833     //
 834     VMReg r_1 = regs[i].first();
 835     VMReg r_2 = regs[i].second();
 836     if (!r_1->is_valid()) {
 837       assert(!r_2->is_valid(), "");
 838       continue;
 839     }
 840     if (r_1->is_stack()) {
 841       // Convert stack slot to an SP offset (+ wordSize to account for return address )
 842       int st_off = regs[i].first()->reg2stack()*VMRegImpl::stack_slot_size + wordSize;
 843 
 844       // We can use r13 as a temp here because compiled code doesn't need r13 as an input
 845       // and if we end up going thru a c2i because of a miss a reasonable value of r13
 846       // will be generated.
 847       if (!r_2->is_valid()) {
 848         // sign extend???
 849         __ movl(r13, Address(saved_sp, ld_off));
 850         __ movptr(Address(rsp, st_off), r13);
 851       } else {
 852         //
 853         // We are using two optoregs. This can be either T_OBJECT, T_ADDRESS, T_LONG, or T_DOUBLE
 854         // the interpreter allocates two slots but only uses one for thr T_LONG or T_DOUBLE case
 855         // So we must adjust where to pick up the data to match the interpreter.
 856         //
 857         // Interpreter local[n] == MSW, local[n+1] == LSW however locals
 858         // are accessed as negative so LSW is at LOW address
 859 
 860         // ld_off is MSW so get LSW
 861         const int offset = (sig_bt[i]==T_LONG||sig_bt[i]==T_DOUBLE)?
 862                            next_off : ld_off;
 863         __ movq(r13, Address(saved_sp, offset));
 864         // st_off is LSW (i.e. reg.first())
 865         __ movq(Address(rsp, st_off), r13);
 866       }
 867     } else if (r_1->is_Register()) {  // Register argument
 868       Register r = r_1->as_Register();
 869       assert(r != rax, "must be different");
 870       if (r_2->is_valid()) {
 871         //
 872         // We are using two VMRegs. This can be either T_OBJECT, T_ADDRESS, T_LONG, or T_DOUBLE
 873         // the interpreter allocates two slots but only uses one for thr T_LONG or T_DOUBLE case
 874         // So we must adjust where to pick up the data to match the interpreter.
 875 
 876         const int offset = (sig_bt[i]==T_LONG||sig_bt[i]==T_DOUBLE)?
 877                            next_off : ld_off;
 878 
 879         // this can be a misaligned move
 880         __ movq(r, Address(saved_sp, offset));
 881       } else {
 882         // sign extend and use a full word?
 883         __ movl(r, Address(saved_sp, ld_off));
 884       }
 885     } else {
 886       if (!r_2->is_valid()) {
 887         __ movflt(r_1->as_XMMRegister(), Address(saved_sp, ld_off));
 888       } else {
 889         __ movdbl(r_1->as_XMMRegister(), Address(saved_sp, next_off));
 890       }
 891     }
 892   }
 893 
 894   // 6243940 We might end up in handle_wrong_method if
 895   // the callee is deoptimized as we race thru here. If that
 896   // happens we don't want to take a safepoint because the
 897   // caller frame will look interpreted and arguments are now
 898   // "compiled" so it is much better to make this transition
 899   // invisible to the stack walking code. Unfortunately if
 900   // we try and find the callee by normal means a safepoint
 901   // is possible. So we stash the desired callee in the thread
 902   // and the vm will find there should this case occur.
 903 
 904   __ movptr(Address(r15_thread, JavaThread::callee_target_offset()), rbx);
 905 
 906   // put Method* where a c2i would expect should we end up there
 907   // only needed becaus eof c2 resolve stubs return Method* as a result in
 908   // rax
 909   __ mov(rax, rbx);
 910   __ jmp(r11);
 911 }
 912 
 913 // ---------------------------------------------------------------
 914 AdapterHandlerEntry* SharedRuntime::generate_i2c2i_adapters(MacroAssembler *masm,
 915                                                             int total_args_passed,
 916                                                             int comp_args_on_stack,
 917                                                             const BasicType *sig_bt,
 918                                                             const VMRegPair *regs,
 919                                                             AdapterFingerPrint* fingerprint) {
 920   address i2c_entry = __ pc();
 921 
 922   gen_i2c_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs);
 923 
 924   // -------------------------------------------------------------------------
 925   // Generate a C2I adapter.  On entry we know rbx holds the Method* during calls
 926   // to the interpreter.  The args start out packed in the compiled layout.  They
 927   // need to be unpacked into the interpreter layout.  This will almost always
 928   // require some stack space.  We grow the current (compiled) stack, then repack
 929   // the args.  We  finally end in a jump to the generic interpreter entry point.
 930   // On exit from the interpreter, the interpreter will restore our SP (lest the
 931   // compiled code, which relys solely on SP and not RBP, get sick).
 932 
 933   address c2i_unverified_entry = __ pc();
 934   Label skip_fixup;
 935   Label ok;
 936 
 937   Register holder = rax;
 938   Register receiver = j_rarg0;
 939   Register temp = rbx;
 940 
 941   {
 942     __ load_klass(temp, receiver);
 943     __ cmpptr(temp, Address(holder, CompiledICHolder::holder_klass_offset()));
 944     __ movptr(rbx, Address(holder, CompiledICHolder::holder_method_offset()));
 945     __ jcc(Assembler::equal, ok);
 946     __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 947 
 948     __ bind(ok);
 949     // Method might have been compiled since the call site was patched to
 950     // interpreted if that is the case treat it as a miss so we can get
 951     // the call site corrected.
 952     __ cmpptr(Address(rbx, in_bytes(Method::code_offset())), (int32_t)NULL_WORD);
 953     __ jcc(Assembler::equal, skip_fixup);
 954     __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 955   }
 956 
 957   address c2i_entry = __ pc();
 958 
 959   gen_c2i_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs, skip_fixup);
 960 
 961   __ flush();
 962   return AdapterHandlerLibrary::new_entry(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry);
 963 }
 964 
 965 int SharedRuntime::c_calling_convention(const BasicType *sig_bt,
 966                                          VMRegPair *regs,
 967                                          VMRegPair *regs2,
 968                                          int total_args_passed) {
 969   assert(regs2 == NULL, "not needed on x86");
 970 // We return the amount of VMRegImpl stack slots we need to reserve for all
 971 // the arguments NOT counting out_preserve_stack_slots.
 972 
 973 // NOTE: These arrays will have to change when c1 is ported
 974 #ifdef _WIN64
 975     static const Register INT_ArgReg[Argument::n_int_register_parameters_c] = {
 976       c_rarg0, c_rarg1, c_rarg2, c_rarg3
 977     };
 978     static const XMMRegister FP_ArgReg[Argument::n_float_register_parameters_c] = {
 979       c_farg0, c_farg1, c_farg2, c_farg3
 980     };
 981 #else
 982     static const Register INT_ArgReg[Argument::n_int_register_parameters_c] = {
 983       c_rarg0, c_rarg1, c_rarg2, c_rarg3, c_rarg4, c_rarg5
 984     };
 985     static const XMMRegister FP_ArgReg[Argument::n_float_register_parameters_c] = {
 986       c_farg0, c_farg1, c_farg2, c_farg3,
 987       c_farg4, c_farg5, c_farg6, c_farg7
 988     };
 989 #endif // _WIN64
 990 
 991 
 992     uint int_args = 0;
 993     uint fp_args = 0;
 994     uint stk_args = 0; // inc by 2 each time
 995 
 996     for (int i = 0; i < total_args_passed; i++) {
 997       switch (sig_bt[i]) {
 998       case T_BOOLEAN:
 999       case T_CHAR:
1000       case T_BYTE:
1001       case T_SHORT:
1002       case T_INT:
1003         if (int_args < Argument::n_int_register_parameters_c) {
1004           regs[i].set1(INT_ArgReg[int_args++]->as_VMReg());
1005 #ifdef _WIN64
1006           fp_args++;
1007           // Allocate slots for callee to stuff register args the stack.
1008           stk_args += 2;
1009 #endif
1010         } else {
1011           regs[i].set1(VMRegImpl::stack2reg(stk_args));
1012           stk_args += 2;
1013         }
1014         break;
1015       case T_LONG:
1016         assert(sig_bt[i + 1] == T_VOID, "expecting half");
1017         // fall through
1018       case T_OBJECT:
1019       case T_ARRAY:
1020       case T_ADDRESS:
1021       case T_METADATA:
1022         if (int_args < Argument::n_int_register_parameters_c) {
1023           regs[i].set2(INT_ArgReg[int_args++]->as_VMReg());
1024 #ifdef _WIN64
1025           fp_args++;
1026           stk_args += 2;
1027 #endif
1028         } else {
1029           regs[i].set2(VMRegImpl::stack2reg(stk_args));
1030           stk_args += 2;
1031         }
1032         break;
1033       case T_FLOAT:
1034         if (fp_args < Argument::n_float_register_parameters_c) {
1035           regs[i].set1(FP_ArgReg[fp_args++]->as_VMReg());
1036 #ifdef _WIN64
1037           int_args++;
1038           // Allocate slots for callee to stuff register args the stack.
1039           stk_args += 2;
1040 #endif
1041         } else {
1042           regs[i].set1(VMRegImpl::stack2reg(stk_args));
1043           stk_args += 2;
1044         }
1045         break;
1046       case T_DOUBLE:
1047         assert(sig_bt[i + 1] == T_VOID, "expecting half");
1048         if (fp_args < Argument::n_float_register_parameters_c) {
1049           regs[i].set2(FP_ArgReg[fp_args++]->as_VMReg());
1050 #ifdef _WIN64
1051           int_args++;
1052           // Allocate slots for callee to stuff register args the stack.
1053           stk_args += 2;
1054 #endif
1055         } else {
1056           regs[i].set2(VMRegImpl::stack2reg(stk_args));
1057           stk_args += 2;
1058         }
1059         break;
1060       case T_VOID: // Halves of longs and doubles
1061         assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
1062         regs[i].set_bad();
1063         break;
1064       default:
1065         ShouldNotReachHere();
1066         break;
1067       }
1068     }
1069 #ifdef _WIN64
1070   // windows abi requires that we always allocate enough stack space
1071   // for 4 64bit registers to be stored down.
1072   if (stk_args < 8) {
1073     stk_args = 8;
1074   }
1075 #endif // _WIN64
1076 
1077   return stk_args;
1078 }
1079 
1080 // On 64 bit we will store integer like items to the stack as
1081 // 64 bits items (sparc abi) even though java would only store
1082 // 32bits for a parameter. On 32bit it will simply be 32 bits
1083 // So this routine will do 32->32 on 32bit and 32->64 on 64bit
1084 static void move32_64(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1085   if (src.first()->is_stack()) {
1086     if (dst.first()->is_stack()) {
1087       // stack to stack
1088       __ movslq(rax, Address(rbp, reg2offset_in(src.first())));
1089       __ movq(Address(rsp, reg2offset_out(dst.first())), rax);
1090     } else {
1091       // stack to reg
1092       __ movslq(dst.first()->as_Register(), Address(rbp, reg2offset_in(src.first())));
1093     }
1094   } else if (dst.first()->is_stack()) {
1095     // reg to stack
1096     // Do we really have to sign extend???
1097     // __ movslq(src.first()->as_Register(), src.first()->as_Register());
1098     __ movq(Address(rsp, reg2offset_out(dst.first())), src.first()->as_Register());
1099   } else {
1100     // Do we really have to sign extend???
1101     // __ movslq(dst.first()->as_Register(), src.first()->as_Register());
1102     if (dst.first() != src.first()) {
1103       __ movq(dst.first()->as_Register(), src.first()->as_Register());
1104     }
1105   }
1106 }
1107 
1108 static void move_ptr(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1109   if (src.first()->is_stack()) {
1110     if (dst.first()->is_stack()) {
1111       // stack to stack
1112       __ movq(rax, Address(rbp, reg2offset_in(src.first())));
1113       __ movq(Address(rsp, reg2offset_out(dst.first())), rax);
1114     } else {
1115       // stack to reg
1116       __ movq(dst.first()->as_Register(), Address(rbp, reg2offset_in(src.first())));
1117     }
1118   } else if (dst.first()->is_stack()) {
1119     // reg to stack
1120     __ movq(Address(rsp, reg2offset_out(dst.first())), src.first()->as_Register());
1121   } else {
1122     if (dst.first() != src.first()) {
1123       __ movq(dst.first()->as_Register(), src.first()->as_Register());
1124     }
1125   }
1126 }
1127 
1128 // An oop arg. Must pass a handle not the oop itself
1129 static void object_move(MacroAssembler* masm,
1130                         OopMap* map,
1131                         int oop_handle_offset,
1132                         int framesize_in_slots,
1133                         VMRegPair src,
1134                         VMRegPair dst,
1135                         bool is_receiver,
1136                         int* receiver_offset) {
1137 
1138   // must pass a handle. First figure out the location we use as a handle
1139 
1140   Register rHandle = dst.first()->is_stack() ? rax : dst.first()->as_Register();
1141 
1142   // See if oop is NULL if it is we need no handle
1143 
1144   if (src.first()->is_stack()) {
1145 
1146     // Oop is already on the stack as an argument
1147     int offset_in_older_frame = src.first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
1148     map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + framesize_in_slots));
1149     if (is_receiver) {
1150       *receiver_offset = (offset_in_older_frame + framesize_in_slots) * VMRegImpl::stack_slot_size;
1151     }
1152 
1153     __ cmpptr(Address(rbp, reg2offset_in(src.first())), (int32_t)NULL_WORD);
1154     __ lea(rHandle, Address(rbp, reg2offset_in(src.first())));
1155     // conditionally move a NULL
1156     __ cmovptr(Assembler::equal, rHandle, Address(rbp, reg2offset_in(src.first())));
1157   } else {
1158 
1159     // Oop is in an a register we must store it to the space we reserve
1160     // on the stack for oop_handles and pass a handle if oop is non-NULL
1161 
1162     const Register rOop = src.first()->as_Register();
1163     int oop_slot;
1164     if (rOop == j_rarg0)
1165       oop_slot = 0;
1166     else if (rOop == j_rarg1)
1167       oop_slot = 1;
1168     else if (rOop == j_rarg2)
1169       oop_slot = 2;
1170     else if (rOop == j_rarg3)
1171       oop_slot = 3;
1172     else if (rOop == j_rarg4)
1173       oop_slot = 4;
1174     else {
1175       assert(rOop == j_rarg5, "wrong register");
1176       oop_slot = 5;
1177     }
1178 
1179     oop_slot = oop_slot * VMRegImpl::slots_per_word + oop_handle_offset;
1180     int offset = oop_slot*VMRegImpl::stack_slot_size;
1181 
1182     map->set_oop(VMRegImpl::stack2reg(oop_slot));
1183     // Store oop in handle area, may be NULL
1184     __ movptr(Address(rsp, offset), rOop);
1185     if (is_receiver) {
1186       *receiver_offset = offset;
1187     }
1188 
1189     __ cmpptr(rOop, (int32_t)NULL_WORD);
1190     __ lea(rHandle, Address(rsp, offset));
1191     // conditionally move a NULL from the handle area where it was just stored
1192     __ cmovptr(Assembler::equal, rHandle, Address(rsp, offset));
1193   }
1194 
1195   // If arg is on the stack then place it otherwise it is already in correct reg.
1196   if (dst.first()->is_stack()) {
1197     __ movptr(Address(rsp, reg2offset_out(dst.first())), rHandle);
1198   }
1199 }
1200 
1201 // A float arg may have to do float reg int reg conversion
1202 static void float_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1203   assert(!src.second()->is_valid() && !dst.second()->is_valid(), "bad float_move");
1204 
1205   // The calling conventions assures us that each VMregpair is either
1206   // all really one physical register or adjacent stack slots.
1207   // This greatly simplifies the cases here compared to sparc.
1208 
1209   if (src.first()->is_stack()) {
1210     if (dst.first()->is_stack()) {
1211       __ movl(rax, Address(rbp, reg2offset_in(src.first())));
1212       __ movptr(Address(rsp, reg2offset_out(dst.first())), rax);
1213     } else {
1214       // stack to reg
1215       assert(dst.first()->is_XMMRegister(), "only expect xmm registers as parameters");
1216       __ movflt(dst.first()->as_XMMRegister(), Address(rbp, reg2offset_in(src.first())));
1217     }
1218   } else if (dst.first()->is_stack()) {
1219     // reg to stack
1220     assert(src.first()->is_XMMRegister(), "only expect xmm registers as parameters");
1221     __ movflt(Address(rsp, reg2offset_out(dst.first())), src.first()->as_XMMRegister());
1222   } else {
1223     // reg to reg
1224     // In theory these overlap but the ordering is such that this is likely a nop
1225     if ( src.first() != dst.first()) {
1226       __ movdbl(dst.first()->as_XMMRegister(),  src.first()->as_XMMRegister());
1227     }
1228   }
1229 }
1230 
1231 // A long move
1232 static void long_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1233 
1234   // The calling conventions assures us that each VMregpair is either
1235   // all really one physical register or adjacent stack slots.
1236   // This greatly simplifies the cases here compared to sparc.
1237 
1238   if (src.is_single_phys_reg() ) {
1239     if (dst.is_single_phys_reg()) {
1240       if (dst.first() != src.first()) {
1241         __ mov(dst.first()->as_Register(), src.first()->as_Register());
1242       }
1243     } else {
1244       assert(dst.is_single_reg(), "not a stack pair");
1245       __ movq(Address(rsp, reg2offset_out(dst.first())), src.first()->as_Register());
1246     }
1247   } else if (dst.is_single_phys_reg()) {
1248     assert(src.is_single_reg(),  "not a stack pair");
1249     __ movq(dst.first()->as_Register(), Address(rbp, reg2offset_out(src.first())));
1250   } else {
1251     assert(src.is_single_reg() && dst.is_single_reg(), "not stack pairs");
1252     __ movq(rax, Address(rbp, reg2offset_in(src.first())));
1253     __ movq(Address(rsp, reg2offset_out(dst.first())), rax);
1254   }
1255 }
1256 
1257 // A double move
1258 static void double_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1259 
1260   // The calling conventions assures us that each VMregpair is either
1261   // all really one physical register or adjacent stack slots.
1262   // This greatly simplifies the cases here compared to sparc.
1263 
1264   if (src.is_single_phys_reg() ) {
1265     if (dst.is_single_phys_reg()) {
1266       // In theory these overlap but the ordering is such that this is likely a nop
1267       if ( src.first() != dst.first()) {
1268         __ movdbl(dst.first()->as_XMMRegister(), src.first()->as_XMMRegister());
1269       }
1270     } else {
1271       assert(dst.is_single_reg(), "not a stack pair");
1272       __ movdbl(Address(rsp, reg2offset_out(dst.first())), src.first()->as_XMMRegister());
1273     }
1274   } else if (dst.is_single_phys_reg()) {
1275     assert(src.is_single_reg(),  "not a stack pair");
1276     __ movdbl(dst.first()->as_XMMRegister(), Address(rbp, reg2offset_out(src.first())));
1277   } else {
1278     assert(src.is_single_reg() && dst.is_single_reg(), "not stack pairs");
1279     __ movq(rax, Address(rbp, reg2offset_in(src.first())));
1280     __ movq(Address(rsp, reg2offset_out(dst.first())), rax);
1281   }
1282 }
1283 
1284 
1285 void SharedRuntime::save_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1286   // We always ignore the frame_slots arg and just use the space just below frame pointer
1287   // which by this time is free to use
1288   switch (ret_type) {
1289   case T_FLOAT:
1290     __ movflt(Address(rbp, -wordSize), xmm0);
1291     break;
1292   case T_DOUBLE:
1293     __ movdbl(Address(rbp, -wordSize), xmm0);
1294     break;
1295   case T_VOID:  break;
1296   default: {
1297     __ movptr(Address(rbp, -wordSize), rax);
1298     }
1299   }
1300 }
1301 
1302 void SharedRuntime::restore_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1303   // We always ignore the frame_slots arg and just use the space just below frame pointer
1304   // which by this time is free to use
1305   switch (ret_type) {
1306   case T_FLOAT:
1307     __ movflt(xmm0, Address(rbp, -wordSize));
1308     break;
1309   case T_DOUBLE:
1310     __ movdbl(xmm0, Address(rbp, -wordSize));
1311     break;
1312   case T_VOID:  break;
1313   default: {
1314     __ movptr(rax, Address(rbp, -wordSize));
1315     }
1316   }
1317 }
1318 
1319 static void save_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
1320     for ( int i = first_arg ; i < arg_count ; i++ ) {
1321       if (args[i].first()->is_Register()) {
1322         __ push(args[i].first()->as_Register());
1323       } else if (args[i].first()->is_XMMRegister()) {
1324         __ subptr(rsp, 2*wordSize);
1325         __ movdbl(Address(rsp, 0), args[i].first()->as_XMMRegister());
1326       }
1327     }
1328 }
1329 
1330 static void restore_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
1331     for ( int i = arg_count - 1 ; i >= first_arg ; i-- ) {
1332       if (args[i].first()->is_Register()) {
1333         __ pop(args[i].first()->as_Register());
1334       } else if (args[i].first()->is_XMMRegister()) {
1335         __ movdbl(args[i].first()->as_XMMRegister(), Address(rsp, 0));
1336         __ addptr(rsp, 2*wordSize);
1337       }
1338     }
1339 }
1340 
1341 
1342 static void save_or_restore_arguments(MacroAssembler* masm,
1343                                       const int stack_slots,
1344                                       const int total_in_args,
1345                                       const int arg_save_area,
1346                                       OopMap* map,
1347                                       VMRegPair* in_regs,
1348                                       BasicType* in_sig_bt) {
1349   // if map is non-NULL then the code should store the values,
1350   // otherwise it should load them.
1351   int slot = arg_save_area;
1352   // Save down double word first
1353   for ( int i = 0; i < total_in_args; i++) {
1354     if (in_regs[i].first()->is_XMMRegister() && in_sig_bt[i] == T_DOUBLE) {
1355       int offset = slot * VMRegImpl::stack_slot_size;
1356       slot += VMRegImpl::slots_per_word;
1357       assert(slot <= stack_slots, "overflow");
1358       if (map != NULL) {
1359         __ movdbl(Address(rsp, offset), in_regs[i].first()->as_XMMRegister());
1360       } else {
1361         __ movdbl(in_regs[i].first()->as_XMMRegister(), Address(rsp, offset));
1362       }
1363     }
1364     if (in_regs[i].first()->is_Register() &&
1365         (in_sig_bt[i] == T_LONG || in_sig_bt[i] == T_ARRAY)) {
1366       int offset = slot * VMRegImpl::stack_slot_size;
1367       if (map != NULL) {
1368         __ movq(Address(rsp, offset), in_regs[i].first()->as_Register());
1369         if (in_sig_bt[i] == T_ARRAY) {
1370           map->set_oop(VMRegImpl::stack2reg(slot));;
1371         }
1372       } else {
1373         __ movq(in_regs[i].first()->as_Register(), Address(rsp, offset));
1374       }
1375       slot += VMRegImpl::slots_per_word;
1376     }
1377   }
1378   // Save or restore single word registers
1379   for ( int i = 0; i < total_in_args; i++) {
1380     if (in_regs[i].first()->is_Register()) {
1381       int offset = slot * VMRegImpl::stack_slot_size;
1382       slot++;
1383       assert(slot <= stack_slots, "overflow");
1384 
1385       // Value is in an input register pass we must flush it to the stack
1386       const Register reg = in_regs[i].first()->as_Register();
1387       switch (in_sig_bt[i]) {
1388         case T_BOOLEAN:
1389         case T_CHAR:
1390         case T_BYTE:
1391         case T_SHORT:
1392         case T_INT:
1393           if (map != NULL) {
1394             __ movl(Address(rsp, offset), reg);
1395           } else {
1396             __ movl(reg, Address(rsp, offset));
1397           }
1398           break;
1399         case T_ARRAY:
1400         case T_LONG:
1401           // handled above
1402           break;
1403         case T_OBJECT:
1404         default: ShouldNotReachHere();
1405       }
1406     } else if (in_regs[i].first()->is_XMMRegister()) {
1407       if (in_sig_bt[i] == T_FLOAT) {
1408         int offset = slot * VMRegImpl::stack_slot_size;
1409         slot++;
1410         assert(slot <= stack_slots, "overflow");
1411         if (map != NULL) {
1412           __ movflt(Address(rsp, offset), in_regs[i].first()->as_XMMRegister());
1413         } else {
1414           __ movflt(in_regs[i].first()->as_XMMRegister(), Address(rsp, offset));
1415         }
1416       }
1417     } else if (in_regs[i].first()->is_stack()) {
1418       if (in_sig_bt[i] == T_ARRAY && map != NULL) {
1419         int offset_in_older_frame = in_regs[i].first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
1420         map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + stack_slots));
1421       }
1422     }
1423   }
1424 }
1425 
1426 
1427 // Check GCLocker::needs_gc and enter the runtime if it's true.  This
1428 // keeps a new JNI critical region from starting until a GC has been
1429 // forced.  Save down any oops in registers and describe them in an
1430 // OopMap.
1431 static void check_needs_gc_for_critical_native(MacroAssembler* masm,
1432                                                int stack_slots,
1433                                                int total_c_args,
1434                                                int total_in_args,
1435                                                int arg_save_area,
1436                                                OopMapSet* oop_maps,
1437                                                VMRegPair* in_regs,
1438                                                BasicType* in_sig_bt) {
1439   __ block_comment("check GCLocker::needs_gc");
1440   Label cont;
1441   __ cmp8(ExternalAddress((address)GCLocker::needs_gc_address()), false);
1442   __ jcc(Assembler::equal, cont);
1443 
1444   // Save down any incoming oops and call into the runtime to halt for a GC
1445 
1446   OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1447   save_or_restore_arguments(masm, stack_slots, total_in_args,
1448                             arg_save_area, map, in_regs, in_sig_bt);
1449 
1450   address the_pc = __ pc();
1451   oop_maps->add_gc_map( __ offset(), map);
1452   __ set_last_Java_frame(rsp, noreg, the_pc);
1453 
1454   __ block_comment("block_for_jni_critical");
1455   __ movptr(c_rarg0, r15_thread);
1456   __ mov(r12, rsp); // remember sp
1457   __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
1458   __ andptr(rsp, -16); // align stack as required by ABI
1459   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::block_for_jni_critical)));
1460   __ mov(rsp, r12); // restore sp
1461   __ reinit_heapbase();
1462 
1463   __ reset_last_Java_frame(false, true);
1464 
1465   save_or_restore_arguments(masm, stack_slots, total_in_args,
1466                             arg_save_area, NULL, in_regs, in_sig_bt);
1467 
1468   __ bind(cont);
1469 #ifdef ASSERT
1470   if (StressCriticalJNINatives) {
1471     // Stress register saving
1472     OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1473     save_or_restore_arguments(masm, stack_slots, total_in_args,
1474                               arg_save_area, map, in_regs, in_sig_bt);
1475     // Destroy argument registers
1476     for (int i = 0; i < total_in_args - 1; i++) {
1477       if (in_regs[i].first()->is_Register()) {
1478         const Register reg = in_regs[i].first()->as_Register();
1479         __ xorptr(reg, reg);
1480       } else if (in_regs[i].first()->is_XMMRegister()) {
1481         __ xorpd(in_regs[i].first()->as_XMMRegister(), in_regs[i].first()->as_XMMRegister());
1482       } else if (in_regs[i].first()->is_FloatRegister()) {
1483         ShouldNotReachHere();
1484       } else if (in_regs[i].first()->is_stack()) {
1485         // Nothing to do
1486       } else {
1487         ShouldNotReachHere();
1488       }
1489       if (in_sig_bt[i] == T_LONG || in_sig_bt[i] == T_DOUBLE) {
1490         i++;
1491       }
1492     }
1493 
1494     save_or_restore_arguments(masm, stack_slots, total_in_args,
1495                               arg_save_area, NULL, in_regs, in_sig_bt);
1496   }
1497 #endif
1498 }
1499 
1500 // Unpack an array argument into a pointer to the body and the length
1501 // if the array is non-null, otherwise pass 0 for both.
1502 static void unpack_array_argument(MacroAssembler* masm, VMRegPair reg, BasicType in_elem_type, VMRegPair body_arg, VMRegPair length_arg) {
1503   Register tmp_reg = rax;
1504   assert(!body_arg.first()->is_Register() || body_arg.first()->as_Register() != tmp_reg,
1505          "possible collision");
1506   assert(!length_arg.first()->is_Register() || length_arg.first()->as_Register() != tmp_reg,
1507          "possible collision");
1508 
1509   __ block_comment("unpack_array_argument {");
1510 
1511   // Pass the length, ptr pair
1512   Label is_null, done;
1513   VMRegPair tmp;
1514   tmp.set_ptr(tmp_reg->as_VMReg());
1515   if (reg.first()->is_stack()) {
1516     // Load the arg up from the stack
1517     move_ptr(masm, reg, tmp);
1518     reg = tmp;
1519   }
1520   __ testptr(reg.first()->as_Register(), reg.first()->as_Register());
1521   __ jccb(Assembler::equal, is_null);
1522   __ lea(tmp_reg, Address(reg.first()->as_Register(), arrayOopDesc::base_offset_in_bytes(in_elem_type)));
1523   move_ptr(masm, tmp, body_arg);
1524   // load the length relative to the body.
1525   __ movl(tmp_reg, Address(tmp_reg, arrayOopDesc::length_offset_in_bytes() -
1526                            arrayOopDesc::base_offset_in_bytes(in_elem_type)));
1527   move32_64(masm, tmp, length_arg);
1528   __ jmpb(done);
1529   __ bind(is_null);
1530   // Pass zeros
1531   __ xorptr(tmp_reg, tmp_reg);
1532   move_ptr(masm, tmp, body_arg);
1533   move32_64(masm, tmp, length_arg);
1534   __ bind(done);
1535 
1536   __ block_comment("} unpack_array_argument");
1537 }
1538 
1539 
1540 // Different signatures may require very different orders for the move
1541 // to avoid clobbering other arguments.  There's no simple way to
1542 // order them safely.  Compute a safe order for issuing stores and
1543 // break any cycles in those stores.  This code is fairly general but
1544 // it's not necessary on the other platforms so we keep it in the
1545 // platform dependent code instead of moving it into a shared file.
1546 // (See bugs 7013347 & 7145024.)
1547 // Note that this code is specific to LP64.
1548 class ComputeMoveOrder: public StackObj {
1549   class MoveOperation: public ResourceObj {
1550     friend class ComputeMoveOrder;
1551    private:
1552     VMRegPair        _src;
1553     VMRegPair        _dst;
1554     int              _src_index;
1555     int              _dst_index;
1556     bool             _processed;
1557     MoveOperation*  _next;
1558     MoveOperation*  _prev;
1559 
1560     static int get_id(VMRegPair r) {
1561       return r.first()->value();
1562     }
1563 
1564    public:
1565     MoveOperation(int src_index, VMRegPair src, int dst_index, VMRegPair dst):
1566       _src(src)
1567     , _src_index(src_index)
1568     , _dst(dst)
1569     , _dst_index(dst_index)
1570     , _next(NULL)
1571     , _prev(NULL)
1572     , _processed(false) {
1573     }
1574 
1575     VMRegPair src() const              { return _src; }
1576     int src_id() const                 { return get_id(src()); }
1577     int src_index() const              { return _src_index; }
1578     VMRegPair dst() const              { return _dst; }
1579     void set_dst(int i, VMRegPair dst) { _dst_index = i, _dst = dst; }
1580     int dst_index() const              { return _dst_index; }
1581     int dst_id() const                 { return get_id(dst()); }
1582     MoveOperation* next() const       { return _next; }
1583     MoveOperation* prev() const       { return _prev; }
1584     void set_processed()               { _processed = true; }
1585     bool is_processed() const          { return _processed; }
1586 
1587     // insert
1588     void break_cycle(VMRegPair temp_register) {
1589       // create a new store following the last store
1590       // to move from the temp_register to the original
1591       MoveOperation* new_store = new MoveOperation(-1, temp_register, dst_index(), dst());
1592 
1593       // break the cycle of links and insert new_store at the end
1594       // break the reverse link.
1595       MoveOperation* p = prev();
1596       assert(p->next() == this, "must be");
1597       _prev = NULL;
1598       p->_next = new_store;
1599       new_store->_prev = p;
1600 
1601       // change the original store to save it's value in the temp.
1602       set_dst(-1, temp_register);
1603     }
1604 
1605     void link(GrowableArray<MoveOperation*>& killer) {
1606       // link this store in front the store that it depends on
1607       MoveOperation* n = killer.at_grow(src_id(), NULL);
1608       if (n != NULL) {
1609         assert(_next == NULL && n->_prev == NULL, "shouldn't have been set yet");
1610         _next = n;
1611         n->_prev = this;
1612       }
1613     }
1614   };
1615 
1616  private:
1617   GrowableArray<MoveOperation*> edges;
1618 
1619  public:
1620   ComputeMoveOrder(int total_in_args, VMRegPair* in_regs, int total_c_args, VMRegPair* out_regs,
1621                     BasicType* in_sig_bt, GrowableArray<int>& arg_order, VMRegPair tmp_vmreg) {
1622     // Move operations where the dest is the stack can all be
1623     // scheduled first since they can't interfere with the other moves.
1624     for (int i = total_in_args - 1, c_arg = total_c_args - 1; i >= 0; i--, c_arg--) {
1625       if (in_sig_bt[i] == T_ARRAY) {
1626         c_arg--;
1627         if (out_regs[c_arg].first()->is_stack() &&
1628             out_regs[c_arg + 1].first()->is_stack()) {
1629           arg_order.push(i);
1630           arg_order.push(c_arg);
1631         } else {
1632           if (out_regs[c_arg].first()->is_stack() ||
1633               in_regs[i].first() == out_regs[c_arg].first()) {
1634             add_edge(i, in_regs[i].first(), c_arg, out_regs[c_arg + 1]);
1635           } else {
1636             add_edge(i, in_regs[i].first(), c_arg, out_regs[c_arg]);
1637           }
1638         }
1639       } else if (in_sig_bt[i] == T_VOID) {
1640         arg_order.push(i);
1641         arg_order.push(c_arg);
1642       } else {
1643         if (out_regs[c_arg].first()->is_stack() ||
1644             in_regs[i].first() == out_regs[c_arg].first()) {
1645           arg_order.push(i);
1646           arg_order.push(c_arg);
1647         } else {
1648           add_edge(i, in_regs[i].first(), c_arg, out_regs[c_arg]);
1649         }
1650       }
1651     }
1652     // Break any cycles in the register moves and emit the in the
1653     // proper order.
1654     GrowableArray<MoveOperation*>* stores = get_store_order(tmp_vmreg);
1655     for (int i = 0; i < stores->length(); i++) {
1656       arg_order.push(stores->at(i)->src_index());
1657       arg_order.push(stores->at(i)->dst_index());
1658     }
1659  }
1660 
1661   // Collected all the move operations
1662   void add_edge(int src_index, VMRegPair src, int dst_index, VMRegPair dst) {
1663     if (src.first() == dst.first()) return;
1664     edges.append(new MoveOperation(src_index, src, dst_index, dst));
1665   }
1666 
1667   // Walk the edges breaking cycles between moves.  The result list
1668   // can be walked in order to produce the proper set of loads
1669   GrowableArray<MoveOperation*>* get_store_order(VMRegPair temp_register) {
1670     // Record which moves kill which values
1671     GrowableArray<MoveOperation*> killer;
1672     for (int i = 0; i < edges.length(); i++) {
1673       MoveOperation* s = edges.at(i);
1674       assert(killer.at_grow(s->dst_id(), NULL) == NULL, "only one killer");
1675       killer.at_put_grow(s->dst_id(), s, NULL);
1676     }
1677     assert(killer.at_grow(MoveOperation::get_id(temp_register), NULL) == NULL,
1678            "make sure temp isn't in the registers that are killed");
1679 
1680     // create links between loads and stores
1681     for (int i = 0; i < edges.length(); i++) {
1682       edges.at(i)->link(killer);
1683     }
1684 
1685     // at this point, all the move operations are chained together
1686     // in a doubly linked list.  Processing it backwards finds
1687     // the beginning of the chain, forwards finds the end.  If there's
1688     // a cycle it can be broken at any point,  so pick an edge and walk
1689     // backward until the list ends or we end where we started.
1690     GrowableArray<MoveOperation*>* stores = new GrowableArray<MoveOperation*>();
1691     for (int e = 0; e < edges.length(); e++) {
1692       MoveOperation* s = edges.at(e);
1693       if (!s->is_processed()) {
1694         MoveOperation* start = s;
1695         // search for the beginning of the chain or cycle
1696         while (start->prev() != NULL && start->prev() != s) {
1697           start = start->prev();
1698         }
1699         if (start->prev() == s) {
1700           start->break_cycle(temp_register);
1701         }
1702         // walk the chain forward inserting to store list
1703         while (start != NULL) {
1704           stores->append(start);
1705           start->set_processed();
1706           start = start->next();
1707         }
1708       }
1709     }
1710     return stores;
1711   }
1712 };
1713 
1714 static void verify_oop_args(MacroAssembler* masm,
1715                             const methodHandle& method,
1716                             const BasicType* sig_bt,
1717                             const VMRegPair* regs) {
1718   Register temp_reg = rbx;  // not part of any compiled calling seq
1719   if (VerifyOops) {
1720     for (int i = 0; i < method->size_of_parameters(); i++) {
1721       if (sig_bt[i] == T_OBJECT ||
1722           sig_bt[i] == T_ARRAY) {
1723         VMReg r = regs[i].first();
1724         assert(r->is_valid(), "bad oop arg");
1725         if (r->is_stack()) {
1726           __ movptr(temp_reg, Address(rsp, r->reg2stack() * VMRegImpl::stack_slot_size + wordSize));
1727           __ verify_oop(temp_reg);
1728         } else {
1729           __ verify_oop(r->as_Register());
1730         }
1731       }
1732     }
1733   }
1734 }
1735 
1736 static void gen_special_dispatch(MacroAssembler* masm,
1737                                  methodHandle method,
1738                                  const BasicType* sig_bt,
1739                                  const VMRegPair* regs) {
1740   verify_oop_args(masm, method, sig_bt, regs);
1741   vmIntrinsics::ID iid = method->intrinsic_id();
1742 
1743   // Now write the args into the outgoing interpreter space
1744   bool     has_receiver   = false;
1745   Register receiver_reg   = noreg;
1746   int      member_arg_pos = -1;
1747   Register member_reg     = noreg;
1748   int      ref_kind       = MethodHandles::signature_polymorphic_intrinsic_ref_kind(iid);
1749   if (ref_kind != 0) {
1750     member_arg_pos = method->size_of_parameters() - 1;  // trailing MemberName argument
1751     member_reg = rbx;  // known to be free at this point
1752     has_receiver = MethodHandles::ref_kind_has_receiver(ref_kind);
1753   } else if (iid == vmIntrinsics::_invokeBasic) {
1754     has_receiver = true;
1755   } else {
1756     fatal("unexpected intrinsic id %d", iid);
1757   }
1758 
1759   if (member_reg != noreg) {
1760     // Load the member_arg into register, if necessary.
1761     SharedRuntime::check_member_name_argument_is_last_argument(method, sig_bt, regs);
1762     VMReg r = regs[member_arg_pos].first();
1763     if (r->is_stack()) {
1764       __ movptr(member_reg, Address(rsp, r->reg2stack() * VMRegImpl::stack_slot_size + wordSize));
1765     } else {
1766       // no data motion is needed
1767       member_reg = r->as_Register();
1768     }
1769   }
1770 
1771   if (has_receiver) {
1772     // Make sure the receiver is loaded into a register.
1773     assert(method->size_of_parameters() > 0, "oob");
1774     assert(sig_bt[0] == T_OBJECT, "receiver argument must be an object");
1775     VMReg r = regs[0].first();
1776     assert(r->is_valid(), "bad receiver arg");
1777     if (r->is_stack()) {
1778       // Porting note:  This assumes that compiled calling conventions always
1779       // pass the receiver oop in a register.  If this is not true on some
1780       // platform, pick a temp and load the receiver from stack.
1781       fatal("receiver always in a register");
1782       receiver_reg = j_rarg0;  // known to be free at this point
1783       __ movptr(receiver_reg, Address(rsp, r->reg2stack() * VMRegImpl::stack_slot_size + wordSize));
1784     } else {
1785       // no data motion is needed
1786       receiver_reg = r->as_Register();
1787     }
1788   }
1789 
1790   // Figure out which address we are really jumping to:
1791   MethodHandles::generate_method_handle_dispatch(masm, iid,
1792                                                  receiver_reg, member_reg, /*for_compiler_entry:*/ true);
1793 }
1794 
1795 // ---------------------------------------------------------------------------
1796 // Generate a native wrapper for a given method.  The method takes arguments
1797 // in the Java compiled code convention, marshals them to the native
1798 // convention (handlizes oops, etc), transitions to native, makes the call,
1799 // returns to java state (possibly blocking), unhandlizes any result and
1800 // returns.
1801 //
1802 // Critical native functions are a shorthand for the use of
1803 // GetPrimtiveArrayCritical and disallow the use of any other JNI
1804 // functions.  The wrapper is expected to unpack the arguments before
1805 // passing them to the callee and perform checks before and after the
1806 // native call to ensure that they GCLocker
1807 // lock_critical/unlock_critical semantics are followed.  Some other
1808 // parts of JNI setup are skipped like the tear down of the JNI handle
1809 // block and the check for pending exceptions it's impossible for them
1810 // to be thrown.
1811 //
1812 // They are roughly structured like this:
1813 //    if (GCLocker::needs_gc())
1814 //      SharedRuntime::block_for_jni_critical();
1815 //    tranistion to thread_in_native
1816 //    unpack arrray arguments and call native entry point
1817 //    check for safepoint in progress
1818 //    check if any thread suspend flags are set
1819 //      call into JVM and possible unlock the JNI critical
1820 //      if a GC was suppressed while in the critical native.
1821 //    transition back to thread_in_Java
1822 //    return to caller
1823 //
1824 nmethod* SharedRuntime::generate_native_wrapper(MacroAssembler* masm,
1825                                                 const methodHandle& method,
1826                                                 int compile_id,
1827                                                 BasicType* in_sig_bt,
1828                                                 VMRegPair* in_regs,
1829                                                 BasicType ret_type) {
1830   if (method->is_method_handle_intrinsic()) {
1831     vmIntrinsics::ID iid = method->intrinsic_id();
1832     intptr_t start = (intptr_t)__ pc();
1833     int vep_offset = ((intptr_t)__ pc()) - start;
1834     gen_special_dispatch(masm,
1835                          method,
1836                          in_sig_bt,
1837                          in_regs);
1838     int frame_complete = ((intptr_t)__ pc()) - start;  // not complete, period
1839     __ flush();
1840     int stack_slots = SharedRuntime::out_preserve_stack_slots();  // no out slots at all, actually
1841     return nmethod::new_native_nmethod(method,
1842                                        compile_id,
1843                                        masm->code(),
1844                                        vep_offset,
1845                                        frame_complete,
1846                                        stack_slots / VMRegImpl::slots_per_word,
1847                                        in_ByteSize(-1),
1848                                        in_ByteSize(-1),
1849                                        (OopMapSet*)NULL);
1850   }
1851   bool is_critical_native = true;
1852   address native_func = method->critical_native_function();
1853   if (native_func == NULL) {
1854     native_func = method->native_function();
1855     is_critical_native = false;
1856   }
1857   assert(native_func != NULL, "must have function");
1858 
1859   // An OopMap for lock (and class if static)
1860   OopMapSet *oop_maps = new OopMapSet();
1861   intptr_t start = (intptr_t)__ pc();
1862 
1863   // We have received a description of where all the java arg are located
1864   // on entry to the wrapper. We need to convert these args to where
1865   // the jni function will expect them. To figure out where they go
1866   // we convert the java signature to a C signature by inserting
1867   // the hidden arguments as arg[0] and possibly arg[1] (static method)
1868 
1869   const int total_in_args = method->size_of_parameters();
1870   int total_c_args = total_in_args;
1871   if (!is_critical_native) {
1872     total_c_args += 1;
1873     if (method->is_static()) {
1874       total_c_args++;
1875     }
1876   } else {
1877     for (int i = 0; i < total_in_args; i++) {
1878       if (in_sig_bt[i] == T_ARRAY) {
1879         total_c_args++;
1880       }
1881     }
1882   }
1883 
1884   BasicType* out_sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_c_args);
1885   VMRegPair* out_regs   = NEW_RESOURCE_ARRAY(VMRegPair, total_c_args);
1886   BasicType* in_elem_bt = NULL;
1887 
1888   int argc = 0;
1889   if (!is_critical_native) {
1890     out_sig_bt[argc++] = T_ADDRESS;
1891     if (method->is_static()) {
1892       out_sig_bt[argc++] = T_OBJECT;
1893     }
1894 
1895     for (int i = 0; i < total_in_args ; i++ ) {
1896       out_sig_bt[argc++] = in_sig_bt[i];
1897     }
1898   } else {
1899     Thread* THREAD = Thread::current();
1900     in_elem_bt = NEW_RESOURCE_ARRAY(BasicType, total_in_args);
1901     SignatureStream ss(method->signature());
1902     for (int i = 0; i < total_in_args ; i++ ) {
1903       if (in_sig_bt[i] == T_ARRAY) {
1904         // Arrays are passed as int, elem* pair
1905         out_sig_bt[argc++] = T_INT;
1906         out_sig_bt[argc++] = T_ADDRESS;
1907         Symbol* atype = ss.as_symbol(CHECK_NULL);
1908         const char* at = atype->as_C_string();
1909         if (strlen(at) == 2) {
1910           assert(at[0] == '[', "must be");
1911           switch (at[1]) {
1912             case 'B': in_elem_bt[i]  = T_BYTE; break;
1913             case 'C': in_elem_bt[i]  = T_CHAR; break;
1914             case 'D': in_elem_bt[i]  = T_DOUBLE; break;
1915             case 'F': in_elem_bt[i]  = T_FLOAT; break;
1916             case 'I': in_elem_bt[i]  = T_INT; break;
1917             case 'J': in_elem_bt[i]  = T_LONG; break;
1918             case 'S': in_elem_bt[i]  = T_SHORT; break;
1919             case 'Z': in_elem_bt[i]  = T_BOOLEAN; break;
1920             default: ShouldNotReachHere();
1921           }
1922         }
1923       } else {
1924         out_sig_bt[argc++] = in_sig_bt[i];
1925         in_elem_bt[i] = T_VOID;
1926       }
1927       if (in_sig_bt[i] != T_VOID) {
1928         assert(in_sig_bt[i] == ss.type(), "must match");
1929         ss.next();
1930       }
1931     }
1932   }
1933 
1934   // Now figure out where the args must be stored and how much stack space
1935   // they require.
1936   int out_arg_slots;
1937   out_arg_slots = c_calling_convention(out_sig_bt, out_regs, NULL, total_c_args);
1938 
1939   // Compute framesize for the wrapper.  We need to handlize all oops in
1940   // incoming registers
1941 
1942   // Calculate the total number of stack slots we will need.
1943 
1944   // First count the abi requirement plus all of the outgoing args
1945   int stack_slots = SharedRuntime::out_preserve_stack_slots() + out_arg_slots;
1946 
1947   // Now the space for the inbound oop handle area
1948   int total_save_slots = 6 * VMRegImpl::slots_per_word;  // 6 arguments passed in registers
1949   if (is_critical_native) {
1950     // Critical natives may have to call out so they need a save area
1951     // for register arguments.
1952     int double_slots = 0;
1953     int single_slots = 0;
1954     for ( int i = 0; i < total_in_args; i++) {
1955       if (in_regs[i].first()->is_Register()) {
1956         const Register reg = in_regs[i].first()->as_Register();
1957         switch (in_sig_bt[i]) {
1958           case T_BOOLEAN:
1959           case T_BYTE:
1960           case T_SHORT:
1961           case T_CHAR:
1962           case T_INT:  single_slots++; break;
1963           case T_ARRAY:  // specific to LP64 (7145024)
1964           case T_LONG: double_slots++; break;
1965           default:  ShouldNotReachHere();
1966         }
1967       } else if (in_regs[i].first()->is_XMMRegister()) {
1968         switch (in_sig_bt[i]) {
1969           case T_FLOAT:  single_slots++; break;
1970           case T_DOUBLE: double_slots++; break;
1971           default:  ShouldNotReachHere();
1972         }
1973       } else if (in_regs[i].first()->is_FloatRegister()) {
1974         ShouldNotReachHere();
1975       }
1976     }
1977     total_save_slots = double_slots * 2 + single_slots;
1978     // align the save area
1979     if (double_slots != 0) {
1980       stack_slots = round_to(stack_slots, 2);
1981     }
1982   }
1983 
1984   int oop_handle_offset = stack_slots;
1985   stack_slots += total_save_slots;
1986 
1987   // Now any space we need for handlizing a klass if static method
1988 
1989   int klass_slot_offset = 0;
1990   int klass_offset = -1;
1991   int lock_slot_offset = 0;
1992   bool is_static = false;
1993 
1994   if (method->is_static()) {
1995     klass_slot_offset = stack_slots;
1996     stack_slots += VMRegImpl::slots_per_word;
1997     klass_offset = klass_slot_offset * VMRegImpl::stack_slot_size;
1998     is_static = true;
1999   }
2000 
2001   // Plus a lock if needed
2002 
2003   if (method->is_synchronized()) {
2004     lock_slot_offset = stack_slots;
2005     stack_slots += VMRegImpl::slots_per_word;
2006   }
2007 
2008   // Now a place (+2) to save return values or temp during shuffling
2009   // + 4 for return address (which we own) and saved rbp
2010   stack_slots += 6;
2011 
2012   // Ok The space we have allocated will look like:
2013   //
2014   //
2015   // FP-> |                     |
2016   //      |---------------------|
2017   //      | 2 slots for moves   |
2018   //      |---------------------|
2019   //      | lock box (if sync)  |
2020   //      |---------------------| <- lock_slot_offset
2021   //      | klass (if static)   |
2022   //      |---------------------| <- klass_slot_offset
2023   //      | oopHandle area      |
2024   //      |---------------------| <- oop_handle_offset (6 java arg registers)
2025   //      | outbound memory     |
2026   //      | based arguments     |
2027   //      |                     |
2028   //      |---------------------|
2029   //      |                     |
2030   // SP-> | out_preserved_slots |
2031   //
2032   //
2033 
2034 
2035   // Now compute actual number of stack words we need rounding to make
2036   // stack properly aligned.
2037   stack_slots = round_to(stack_slots, StackAlignmentInSlots);
2038 
2039   int stack_size = stack_slots * VMRegImpl::stack_slot_size;
2040 
2041   // First thing make an ic check to see if we should even be here
2042 
2043   // We are free to use all registers as temps without saving them and
2044   // restoring them except rbp. rbp is the only callee save register
2045   // as far as the interpreter and the compiler(s) are concerned.
2046 
2047 
2048   const Register ic_reg = rax;
2049   const Register receiver = j_rarg0;
2050 
2051   Label hit;
2052   Label exception_pending;
2053 
2054   assert_different_registers(ic_reg, receiver, rscratch1);
2055   __ verify_oop(receiver);
2056   __ load_klass(rscratch1, receiver);
2057   __ cmpq(ic_reg, rscratch1);
2058   __ jcc(Assembler::equal, hit);
2059 
2060   __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
2061 
2062   // Verified entry point must be aligned
2063   __ align(8);
2064 
2065   __ bind(hit);
2066 
2067   int vep_offset = ((intptr_t)__ pc()) - start;
2068 
2069   // The instruction at the verified entry point must be 5 bytes or longer
2070   // because it can be patched on the fly by make_non_entrant. The stack bang
2071   // instruction fits that requirement.
2072 
2073   // Generate stack overflow check
2074 
2075   if (UseStackBanging) {
2076     __ bang_stack_with_offset((int)JavaThread::stack_shadow_zone_size());
2077   } else {
2078     // need a 5 byte instruction to allow MT safe patching to non-entrant
2079     __ fat_nop();
2080   }
2081 
2082   // Generate a new frame for the wrapper.
2083   __ enter();
2084   // -2 because return address is already present and so is saved rbp
2085   __ subptr(rsp, stack_size - 2*wordSize);
2086 
2087   // Frame is now completed as far as size and linkage.
2088   int frame_complete = ((intptr_t)__ pc()) - start;
2089 
2090     if (UseRTMLocking) {
2091       // Abort RTM transaction before calling JNI
2092       // because critical section will be large and will be
2093       // aborted anyway. Also nmethod could be deoptimized.
2094       __ xabort(0);
2095     }
2096 
2097 #ifdef ASSERT
2098     {
2099       Label L;
2100       __ mov(rax, rsp);
2101       __ andptr(rax, -16); // must be 16 byte boundary (see amd64 ABI)
2102       __ cmpptr(rax, rsp);
2103       __ jcc(Assembler::equal, L);
2104       __ stop("improperly aligned stack");
2105       __ bind(L);
2106     }
2107 #endif /* ASSERT */
2108 
2109 
2110   // We use r14 as the oop handle for the receiver/klass
2111   // It is callee save so it survives the call to native
2112 
2113   const Register oop_handle_reg = r14;
2114 
2115   if (is_critical_native) {
2116     check_needs_gc_for_critical_native(masm, stack_slots, total_c_args, total_in_args,
2117                                        oop_handle_offset, oop_maps, in_regs, in_sig_bt);
2118   }
2119 
2120   //
2121   // We immediately shuffle the arguments so that any vm call we have to
2122   // make from here on out (sync slow path, jvmti, etc.) we will have
2123   // captured the oops from our caller and have a valid oopMap for
2124   // them.
2125 
2126   // -----------------
2127   // The Grand Shuffle
2128 
2129   // The Java calling convention is either equal (linux) or denser (win64) than the
2130   // c calling convention. However the because of the jni_env argument the c calling
2131   // convention always has at least one more (and two for static) arguments than Java.
2132   // Therefore if we move the args from java -> c backwards then we will never have
2133   // a register->register conflict and we don't have to build a dependency graph
2134   // and figure out how to break any cycles.
2135   //
2136 
2137   // Record esp-based slot for receiver on stack for non-static methods
2138   int receiver_offset = -1;
2139 
2140   // This is a trick. We double the stack slots so we can claim
2141   // the oops in the caller's frame. Since we are sure to have
2142   // more args than the caller doubling is enough to make
2143   // sure we can capture all the incoming oop args from the
2144   // caller.
2145   //
2146   OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
2147 
2148   // Mark location of rbp (someday)
2149   // map->set_callee_saved(VMRegImpl::stack2reg( stack_slots - 2), stack_slots * 2, 0, vmreg(rbp));
2150 
2151   // Use eax, ebx as temporaries during any memory-memory moves we have to do
2152   // All inbound args are referenced based on rbp and all outbound args via rsp.
2153 
2154 
2155 #ifdef ASSERT
2156   bool reg_destroyed[RegisterImpl::number_of_registers];
2157   bool freg_destroyed[XMMRegisterImpl::number_of_registers];
2158   for ( int r = 0 ; r < RegisterImpl::number_of_registers ; r++ ) {
2159     reg_destroyed[r] = false;
2160   }
2161   for ( int f = 0 ; f < XMMRegisterImpl::number_of_registers ; f++ ) {
2162     freg_destroyed[f] = false;
2163   }
2164 
2165 #endif /* ASSERT */
2166 
2167   // This may iterate in two different directions depending on the
2168   // kind of native it is.  The reason is that for regular JNI natives
2169   // the incoming and outgoing registers are offset upwards and for
2170   // critical natives they are offset down.
2171   GrowableArray<int> arg_order(2 * total_in_args);
2172   VMRegPair tmp_vmreg;
2173   tmp_vmreg.set1(rbx->as_VMReg());
2174 
2175   if (!is_critical_native) {
2176     for (int i = total_in_args - 1, c_arg = total_c_args - 1; i >= 0; i--, c_arg--) {
2177       arg_order.push(i);
2178       arg_order.push(c_arg);
2179     }
2180   } else {
2181     // Compute a valid move order, using tmp_vmreg to break any cycles
2182     ComputeMoveOrder cmo(total_in_args, in_regs, total_c_args, out_regs, in_sig_bt, arg_order, tmp_vmreg);
2183   }
2184 
2185   int temploc = -1;
2186   for (int ai = 0; ai < arg_order.length(); ai += 2) {
2187     int i = arg_order.at(ai);
2188     int c_arg = arg_order.at(ai + 1);
2189     __ block_comment(err_msg("move %d -> %d", i, c_arg));
2190     if (c_arg == -1) {
2191       assert(is_critical_native, "should only be required for critical natives");
2192       // This arg needs to be moved to a temporary
2193       __ mov(tmp_vmreg.first()->as_Register(), in_regs[i].first()->as_Register());
2194       in_regs[i] = tmp_vmreg;
2195       temploc = i;
2196       continue;
2197     } else if (i == -1) {
2198       assert(is_critical_native, "should only be required for critical natives");
2199       // Read from the temporary location
2200       assert(temploc != -1, "must be valid");
2201       i = temploc;
2202       temploc = -1;
2203     }
2204 #ifdef ASSERT
2205     if (in_regs[i].first()->is_Register()) {
2206       assert(!reg_destroyed[in_regs[i].first()->as_Register()->encoding()], "destroyed reg!");
2207     } else if (in_regs[i].first()->is_XMMRegister()) {
2208       assert(!freg_destroyed[in_regs[i].first()->as_XMMRegister()->encoding()], "destroyed reg!");
2209     }
2210     if (out_regs[c_arg].first()->is_Register()) {
2211       reg_destroyed[out_regs[c_arg].first()->as_Register()->encoding()] = true;
2212     } else if (out_regs[c_arg].first()->is_XMMRegister()) {
2213       freg_destroyed[out_regs[c_arg].first()->as_XMMRegister()->encoding()] = true;
2214     }
2215 #endif /* ASSERT */
2216     switch (in_sig_bt[i]) {
2217       case T_ARRAY:
2218         if (is_critical_native) {
2219           unpack_array_argument(masm, in_regs[i], in_elem_bt[i], out_regs[c_arg + 1], out_regs[c_arg]);
2220           c_arg++;
2221 #ifdef ASSERT
2222           if (out_regs[c_arg].first()->is_Register()) {
2223             reg_destroyed[out_regs[c_arg].first()->as_Register()->encoding()] = true;
2224           } else if (out_regs[c_arg].first()->is_XMMRegister()) {
2225             freg_destroyed[out_regs[c_arg].first()->as_XMMRegister()->encoding()] = true;
2226           }
2227 #endif
2228           break;
2229         }
2230       case T_OBJECT:
2231         assert(!is_critical_native, "no oop arguments");
2232         object_move(masm, map, oop_handle_offset, stack_slots, in_regs[i], out_regs[c_arg],
2233                     ((i == 0) && (!is_static)),
2234                     &receiver_offset);
2235         break;
2236       case T_VOID:
2237         break;
2238 
2239       case T_FLOAT:
2240         float_move(masm, in_regs[i], out_regs[c_arg]);
2241           break;
2242 
2243       case T_DOUBLE:
2244         assert( i + 1 < total_in_args &&
2245                 in_sig_bt[i + 1] == T_VOID &&
2246                 out_sig_bt[c_arg+1] == T_VOID, "bad arg list");
2247         double_move(masm, in_regs[i], out_regs[c_arg]);
2248         break;
2249 
2250       case T_LONG :
2251         long_move(masm, in_regs[i], out_regs[c_arg]);
2252         break;
2253 
2254       case T_ADDRESS: assert(false, "found T_ADDRESS in java args");
2255 
2256       default:
2257         move32_64(masm, in_regs[i], out_regs[c_arg]);
2258     }
2259   }
2260 
2261   int c_arg;
2262 
2263   // Pre-load a static method's oop into r14.  Used both by locking code and
2264   // the normal JNI call code.
2265   if (!is_critical_native) {
2266     // point c_arg at the first arg that is already loaded in case we
2267     // need to spill before we call out
2268     c_arg = total_c_args - total_in_args;
2269 
2270     if (method->is_static()) {
2271 
2272       //  load oop into a register
2273       __ movoop(oop_handle_reg, JNIHandles::make_local(method->method_holder()->java_mirror()));
2274 
2275       // Now handlize the static class mirror it's known not-null.
2276       __ movptr(Address(rsp, klass_offset), oop_handle_reg);
2277       map->set_oop(VMRegImpl::stack2reg(klass_slot_offset));
2278 
2279       // Now get the handle
2280       __ lea(oop_handle_reg, Address(rsp, klass_offset));
2281       // store the klass handle as second argument
2282       __ movptr(c_rarg1, oop_handle_reg);
2283       // and protect the arg if we must spill
2284       c_arg--;
2285     }
2286   } else {
2287     // For JNI critical methods we need to save all registers in save_args.
2288     c_arg = 0;
2289   }
2290 
2291   // Change state to native (we save the return address in the thread, since it might not
2292   // be pushed on the stack when we do a a stack traversal). It is enough that the pc()
2293   // points into the right code segment. It does not have to be the correct return pc.
2294   // We use the same pc/oopMap repeatedly when we call out
2295 
2296   intptr_t the_pc = (intptr_t) __ pc();
2297   oop_maps->add_gc_map(the_pc - start, map);
2298 
2299   __ set_last_Java_frame(rsp, noreg, (address)the_pc);
2300 
2301 
2302   // We have all of the arguments setup at this point. We must not touch any register
2303   // argument registers at this point (what if we save/restore them there are no oop?
2304 
2305   {
2306     SkipIfEqual skip(masm, &DTraceMethodProbes, false);
2307     // protect the args we've loaded
2308     save_args(masm, total_c_args, c_arg, out_regs);
2309     __ mov_metadata(c_rarg1, method());
2310     __ call_VM_leaf(
2311       CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry),
2312       r15_thread, c_rarg1);
2313     restore_args(masm, total_c_args, c_arg, out_regs);
2314   }
2315 
2316   // RedefineClasses() tracing support for obsolete method entry
2317   if (RC_TRACE_IN_RANGE(0x00001000, 0x00002000)) {
2318     // protect the args we've loaded
2319     save_args(masm, total_c_args, c_arg, out_regs);
2320     __ mov_metadata(c_rarg1, method());
2321     __ call_VM_leaf(
2322       CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
2323       r15_thread, c_rarg1);
2324     restore_args(masm, total_c_args, c_arg, out_regs);
2325   }
2326 
2327   // Lock a synchronized method
2328 
2329   // Register definitions used by locking and unlocking
2330 
2331   const Register swap_reg = rax;  // Must use rax for cmpxchg instruction
2332   const Register obj_reg  = rbx;  // Will contain the oop
2333   const Register lock_reg = r13;  // Address of compiler lock object (BasicLock)
2334   const Register old_hdr  = r13;  // value of old header at unlock time
2335 
2336   Label slow_path_lock;
2337   Label lock_done;
2338 
2339   if (method->is_synchronized()) {
2340     assert(!is_critical_native, "unhandled");
2341 
2342 
2343     const int mark_word_offset = BasicLock::displaced_header_offset_in_bytes();
2344 
2345     // Get the handle (the 2nd argument)
2346     __ mov(oop_handle_reg, c_rarg1);
2347 
2348     // Get address of the box
2349 
2350     __ lea(lock_reg, Address(rsp, lock_slot_offset * VMRegImpl::stack_slot_size));
2351 
2352     // Load the oop from the handle
2353     __ movptr(obj_reg, Address(oop_handle_reg, 0));
2354 
2355     if (UseBiasedLocking) {
2356       __ biased_locking_enter(lock_reg, obj_reg, swap_reg, rscratch1, false, lock_done, &slow_path_lock);
2357     }
2358 
2359     // Load immediate 1 into swap_reg %rax
2360     __ movl(swap_reg, 1);
2361 
2362     // Load (object->mark() | 1) into swap_reg %rax
2363     __ orptr(swap_reg, Address(obj_reg, 0));
2364 
2365     // Save (object->mark() | 1) into BasicLock's displaced header
2366     __ movptr(Address(lock_reg, mark_word_offset), swap_reg);
2367 
2368     if (os::is_MP()) {
2369       __ lock();
2370     }
2371 
2372     // src -> dest iff dest == rax else rax <- dest
2373     __ cmpxchgptr(lock_reg, Address(obj_reg, 0));
2374     __ jcc(Assembler::equal, lock_done);
2375 
2376     // Hmm should this move to the slow path code area???
2377 
2378     // Test if the oopMark is an obvious stack pointer, i.e.,
2379     //  1) (mark & 3) == 0, and
2380     //  2) rsp <= mark < mark + os::pagesize()
2381     // These 3 tests can be done by evaluating the following
2382     // expression: ((mark - rsp) & (3 - os::vm_page_size())),
2383     // assuming both stack pointer and pagesize have their
2384     // least significant 2 bits clear.
2385     // NOTE: the oopMark is in swap_reg %rax as the result of cmpxchg
2386 
2387     __ subptr(swap_reg, rsp);
2388     __ andptr(swap_reg, 3 - os::vm_page_size());
2389 
2390     // Save the test result, for recursive case, the result is zero
2391     __ movptr(Address(lock_reg, mark_word_offset), swap_reg);
2392     __ jcc(Assembler::notEqual, slow_path_lock);
2393 
2394     // Slow path will re-enter here
2395 
2396     __ bind(lock_done);
2397   }
2398 
2399 
2400   // Finally just about ready to make the JNI call
2401 
2402 
2403   // get JNIEnv* which is first argument to native
2404   if (!is_critical_native) {
2405     __ lea(c_rarg0, Address(r15_thread, in_bytes(JavaThread::jni_environment_offset())));
2406   }
2407 
2408   // Now set thread in native
2409   __ movl(Address(r15_thread, JavaThread::thread_state_offset()), _thread_in_native);
2410 
2411   __ call(RuntimeAddress(native_func));
2412 
2413   // Verify or restore cpu control state after JNI call
2414   __ restore_cpu_control_state_after_jni();
2415 
2416   // Unpack native results.
2417   switch (ret_type) {
2418   case T_BOOLEAN: __ c2bool(rax);            break;
2419   case T_CHAR   : __ movzwl(rax, rax);      break;
2420   case T_BYTE   : __ sign_extend_byte (rax); break;
2421   case T_SHORT  : __ sign_extend_short(rax); break;
2422   case T_INT    : /* nothing to do */        break;
2423   case T_DOUBLE :
2424   case T_FLOAT  :
2425     // Result is in xmm0 we'll save as needed
2426     break;
2427   case T_ARRAY:                 // Really a handle
2428   case T_OBJECT:                // Really a handle
2429       break; // can't de-handlize until after safepoint check
2430   case T_VOID: break;
2431   case T_LONG: break;
2432   default       : ShouldNotReachHere();
2433   }
2434 
2435   // Switch thread to "native transition" state before reading the synchronization state.
2436   // This additional state is necessary because reading and testing the synchronization
2437   // state is not atomic w.r.t. GC, as this scenario demonstrates:
2438   //     Java thread A, in _thread_in_native state, loads _not_synchronized and is preempted.
2439   //     VM thread changes sync state to synchronizing and suspends threads for GC.
2440   //     Thread A is resumed to finish this native method, but doesn't block here since it
2441   //     didn't see any synchronization is progress, and escapes.
2442   __ movl(Address(r15_thread, JavaThread::thread_state_offset()), _thread_in_native_trans);
2443 
2444   if(os::is_MP()) {
2445     if (UseMembar) {
2446       // Force this write out before the read below
2447       __ membar(Assembler::Membar_mask_bits(
2448            Assembler::LoadLoad | Assembler::LoadStore |
2449            Assembler::StoreLoad | Assembler::StoreStore));
2450     } else {
2451       // Write serialization page so VM thread can do a pseudo remote membar.
2452       // We use the current thread pointer to calculate a thread specific
2453       // offset to write to within the page. This minimizes bus traffic
2454       // due to cache line collision.
2455       __ serialize_memory(r15_thread, rcx);
2456     }
2457   }
2458 
2459   Label after_transition;
2460 
2461   // check for safepoint operation in progress and/or pending suspend requests
2462   {
2463     Label Continue;
2464 
2465     __ cmp32(ExternalAddress((address)SafepointSynchronize::address_of_state()),
2466              SafepointSynchronize::_not_synchronized);
2467 
2468     Label L;
2469     __ jcc(Assembler::notEqual, L);
2470     __ cmpl(Address(r15_thread, JavaThread::suspend_flags_offset()), 0);
2471     __ jcc(Assembler::equal, Continue);
2472     __ bind(L);
2473 
2474     // Don't use call_VM as it will see a possible pending exception and forward it
2475     // and never return here preventing us from clearing _last_native_pc down below.
2476     // Also can't use call_VM_leaf either as it will check to see if rsi & rdi are
2477     // preserved and correspond to the bcp/locals pointers. So we do a runtime call
2478     // by hand.
2479     //
2480     save_native_result(masm, ret_type, stack_slots);
2481     __ mov(c_rarg0, r15_thread);
2482     __ mov(r12, rsp); // remember sp
2483     __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
2484     __ andptr(rsp, -16); // align stack as required by ABI
2485     if (!is_critical_native) {
2486       __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans)));
2487     } else {
2488       __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans_and_transition)));
2489     }
2490     __ mov(rsp, r12); // restore sp
2491     __ reinit_heapbase();
2492     // Restore any method result value
2493     restore_native_result(masm, ret_type, stack_slots);
2494 
2495     if (is_critical_native) {
2496       // The call above performed the transition to thread_in_Java so
2497       // skip the transition logic below.
2498       __ jmpb(after_transition);
2499     }
2500 
2501     __ bind(Continue);
2502   }
2503 
2504   // change thread state
2505   __ movl(Address(r15_thread, JavaThread::thread_state_offset()), _thread_in_Java);
2506   __ bind(after_transition);
2507 
2508   Label reguard;
2509   Label reguard_done;
2510   __ cmpl(Address(r15_thread, JavaThread::stack_guard_state_offset()), JavaThread::stack_guard_yellow_reserved_disabled);
2511   __ jcc(Assembler::equal, reguard);
2512   __ bind(reguard_done);
2513 
2514   // native result if any is live
2515 
2516   // Unlock
2517   Label unlock_done;
2518   Label slow_path_unlock;
2519   if (method->is_synchronized()) {
2520 
2521     // Get locked oop from the handle we passed to jni
2522     __ movptr(obj_reg, Address(oop_handle_reg, 0));
2523 
2524     Label done;
2525 
2526     if (UseBiasedLocking) {
2527       __ biased_locking_exit(obj_reg, old_hdr, done);
2528     }
2529 
2530     // Simple recursive lock?
2531 
2532     __ cmpptr(Address(rsp, lock_slot_offset * VMRegImpl::stack_slot_size), (int32_t)NULL_WORD);
2533     __ jcc(Assembler::equal, done);
2534 
2535     // Must save rax if if it is live now because cmpxchg must use it
2536     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
2537       save_native_result(masm, ret_type, stack_slots);
2538     }
2539 
2540 
2541     // get address of the stack lock
2542     __ lea(rax, Address(rsp, lock_slot_offset * VMRegImpl::stack_slot_size));
2543     //  get old displaced header
2544     __ movptr(old_hdr, Address(rax, 0));
2545 
2546     // Atomic swap old header if oop still contains the stack lock
2547     if (os::is_MP()) {
2548       __ lock();
2549     }
2550     __ cmpxchgptr(old_hdr, Address(obj_reg, 0));
2551     __ jcc(Assembler::notEqual, slow_path_unlock);
2552 
2553     // slow path re-enters here
2554     __ bind(unlock_done);
2555     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
2556       restore_native_result(masm, ret_type, stack_slots);
2557     }
2558 
2559     __ bind(done);
2560 
2561   }
2562   {
2563     SkipIfEqual skip(masm, &DTraceMethodProbes, false);
2564     save_native_result(masm, ret_type, stack_slots);
2565     __ mov_metadata(c_rarg1, method());
2566     __ call_VM_leaf(
2567          CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit),
2568          r15_thread, c_rarg1);
2569     restore_native_result(masm, ret_type, stack_slots);
2570   }
2571 
2572   __ reset_last_Java_frame(false, true);
2573 
2574   // Unpack oop result
2575   if (ret_type == T_OBJECT || ret_type == T_ARRAY) {
2576       Label L;
2577       __ testptr(rax, rax);
2578       __ jcc(Assembler::zero, L);
2579       __ movptr(rax, Address(rax, 0));
2580       __ bind(L);
2581       __ verify_oop(rax);
2582   }
2583 
2584   if (!is_critical_native) {
2585     // reset handle block
2586     __ movptr(rcx, Address(r15_thread, JavaThread::active_handles_offset()));
2587     __ movl(Address(rcx, JNIHandleBlock::top_offset_in_bytes()), (int32_t)NULL_WORD);
2588   }
2589 
2590   // pop our frame
2591 
2592   __ leave();
2593 
2594   if (!is_critical_native) {
2595     // Any exception pending?
2596     __ cmpptr(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), (int32_t)NULL_WORD);
2597     __ jcc(Assembler::notEqual, exception_pending);
2598   }
2599 
2600   // Return
2601 
2602   __ ret(0);
2603 
2604   // Unexpected paths are out of line and go here
2605 
2606   if (!is_critical_native) {
2607     // forward the exception
2608     __ bind(exception_pending);
2609 
2610     // and forward the exception
2611     __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2612   }
2613 
2614   // Slow path locking & unlocking
2615   if (method->is_synchronized()) {
2616 
2617     // BEGIN Slow path lock
2618     __ bind(slow_path_lock);
2619 
2620     // has last_Java_frame setup. No exceptions so do vanilla call not call_VM
2621     // args are (oop obj, BasicLock* lock, JavaThread* thread)
2622 
2623     // protect the args we've loaded
2624     save_args(masm, total_c_args, c_arg, out_regs);
2625 
2626     __ mov(c_rarg0, obj_reg);
2627     __ mov(c_rarg1, lock_reg);
2628     __ mov(c_rarg2, r15_thread);
2629 
2630     // Not a leaf but we have last_Java_frame setup as we want
2631     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_locking_C), 3);
2632     restore_args(masm, total_c_args, c_arg, out_regs);
2633 
2634 #ifdef ASSERT
2635     { Label L;
2636     __ cmpptr(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), (int32_t)NULL_WORD);
2637     __ jcc(Assembler::equal, L);
2638     __ stop("no pending exception allowed on exit from monitorenter");
2639     __ bind(L);
2640     }
2641 #endif
2642     __ jmp(lock_done);
2643 
2644     // END Slow path lock
2645 
2646     // BEGIN Slow path unlock
2647     __ bind(slow_path_unlock);
2648 
2649     // If we haven't already saved the native result we must save it now as xmm registers
2650     // are still exposed.
2651 
2652     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2653       save_native_result(masm, ret_type, stack_slots);
2654     }
2655 
2656     __ lea(c_rarg1, Address(rsp, lock_slot_offset * VMRegImpl::stack_slot_size));
2657 
2658     __ mov(c_rarg0, obj_reg);
2659     __ mov(c_rarg2, r15_thread);
2660     __ mov(r12, rsp); // remember sp
2661     __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
2662     __ andptr(rsp, -16); // align stack as required by ABI
2663 
2664     // Save pending exception around call to VM (which contains an EXCEPTION_MARK)
2665     // NOTE that obj_reg == rbx currently
2666     __ movptr(rbx, Address(r15_thread, in_bytes(Thread::pending_exception_offset())));
2667     __ movptr(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), (int32_t)NULL_WORD);
2668 
2669     // args are (oop obj, BasicLock* lock, JavaThread* thread)
2670     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C)));
2671     __ mov(rsp, r12); // restore sp
2672     __ reinit_heapbase();
2673 #ifdef ASSERT
2674     {
2675       Label L;
2676       __ cmpptr(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), (int)NULL_WORD);
2677       __ jcc(Assembler::equal, L);
2678       __ stop("no pending exception allowed on exit complete_monitor_unlocking_C");
2679       __ bind(L);
2680     }
2681 #endif /* ASSERT */
2682 
2683     __ movptr(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), rbx);
2684 
2685     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2686       restore_native_result(masm, ret_type, stack_slots);
2687     }
2688     __ jmp(unlock_done);
2689 
2690     // END Slow path unlock
2691 
2692   } // synchronized
2693 
2694   // SLOW PATH Reguard the stack if needed
2695 
2696   __ bind(reguard);
2697   save_native_result(masm, ret_type, stack_slots);
2698   __ mov(r12, rsp); // remember sp
2699   __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
2700   __ andptr(rsp, -16); // align stack as required by ABI
2701   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages)));
2702   __ mov(rsp, r12); // restore sp
2703   __ reinit_heapbase();
2704   restore_native_result(masm, ret_type, stack_slots);
2705   // and continue
2706   __ jmp(reguard_done);
2707 
2708 
2709 
2710   __ flush();
2711 
2712   nmethod *nm = nmethod::new_native_nmethod(method,
2713                                             compile_id,
2714                                             masm->code(),
2715                                             vep_offset,
2716                                             frame_complete,
2717                                             stack_slots / VMRegImpl::slots_per_word,
2718                                             (is_static ? in_ByteSize(klass_offset) : in_ByteSize(receiver_offset)),
2719                                             in_ByteSize(lock_slot_offset*VMRegImpl::stack_slot_size),
2720                                             oop_maps);
2721 
2722   if (is_critical_native) {
2723     nm->set_lazy_critical_native(true);
2724   }
2725 
2726   return nm;
2727 
2728 }
2729 
2730 // this function returns the adjust size (in number of words) to a c2i adapter
2731 // activation for use during deoptimization
2732 int Deoptimization::last_frame_adjust(int callee_parameters, int callee_locals ) {
2733   return (callee_locals - callee_parameters) * Interpreter::stackElementWords;
2734 }
2735 
2736 
2737 uint SharedRuntime::out_preserve_stack_slots() {
2738   return 0;
2739 }
2740 
2741 //------------------------------generate_deopt_blob----------------------------
2742 void SharedRuntime::generate_deopt_blob() {
2743   // Allocate space for the code
2744   ResourceMark rm;
2745   // Setup code generation tools
2746   int pad = 0;
2747 #if INCLUDE_JVMCI
2748   if (EnableJVMCI) {
2749     pad += 512; // Increase the buffer size when compiling for JVMCI
2750   }
2751 #endif
2752   CodeBuffer buffer("deopt_blob", 2048+pad, 1024);
2753   MacroAssembler* masm = new MacroAssembler(&buffer);
2754   int frame_size_in_words;
2755   OopMap* map = NULL;
2756   OopMapSet *oop_maps = new OopMapSet();
2757 
2758   // -------------
2759   // This code enters when returning to a de-optimized nmethod.  A return
2760   // address has been pushed on the the stack, and return values are in
2761   // registers.
2762   // If we are doing a normal deopt then we were called from the patched
2763   // nmethod from the point we returned to the nmethod. So the return
2764   // address on the stack is wrong by NativeCall::instruction_size
2765   // We will adjust the value so it looks like we have the original return
2766   // address on the stack (like when we eagerly deoptimized).
2767   // In the case of an exception pending when deoptimizing, we enter
2768   // with a return address on the stack that points after the call we patched
2769   // into the exception handler. We have the following register state from,
2770   // e.g., the forward exception stub (see stubGenerator_x86_64.cpp).
2771   //    rax: exception oop
2772   //    rbx: exception handler
2773   //    rdx: throwing pc
2774   // So in this case we simply jam rdx into the useless return address and
2775   // the stack looks just like we want.
2776   //
2777   // At this point we need to de-opt.  We save the argument return
2778   // registers.  We call the first C routine, fetch_unroll_info().  This
2779   // routine captures the return values and returns a structure which
2780   // describes the current frame size and the sizes of all replacement frames.
2781   // The current frame is compiled code and may contain many inlined
2782   // functions, each with their own JVM state.  We pop the current frame, then
2783   // push all the new frames.  Then we call the C routine unpack_frames() to
2784   // populate these frames.  Finally unpack_frames() returns us the new target
2785   // address.  Notice that callee-save registers are BLOWN here; they have
2786   // already been captured in the vframeArray at the time the return PC was
2787   // patched.
2788   address start = __ pc();
2789   Label cont;
2790 
2791   // Prolog for non exception case!
2792 
2793   // Save everything in sight.
2794   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
2795 
2796   // Normal deoptimization.  Save exec mode for unpack_frames.
2797   __ movl(r14, Deoptimization::Unpack_deopt); // callee-saved
2798   __ jmp(cont);
2799 
2800   int reexecute_offset = __ pc() - start;
2801 #if INCLUDE_JVMCI && !defined(COMPILER1)
2802   if (EnableJVMCI && UseJVMCICompiler) {
2803     // JVMCI does not use this kind of deoptimization
2804     __ should_not_reach_here();
2805   }
2806 #endif
2807 
2808   // Reexecute case
2809   // return address is the pc describes what bci to do re-execute at
2810 
2811   // No need to update map as each call to save_live_registers will produce identical oopmap
2812   (void) RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
2813 
2814   __ movl(r14, Deoptimization::Unpack_reexecute); // callee-saved
2815   __ jmp(cont);
2816 
2817 #if INCLUDE_JVMCI
2818   Label after_fetch_unroll_info_call;
2819   int implicit_exception_uncommon_trap_offset = 0;
2820   int uncommon_trap_offset = 0;
2821 
2822   if (EnableJVMCI) {
2823     implicit_exception_uncommon_trap_offset = __ pc() - start;
2824 
2825     __ pushptr(Address(r15_thread, in_bytes(JavaThread::jvmci_implicit_exception_pc_offset())));
2826     __ movptr(Address(r15_thread, in_bytes(JavaThread::jvmci_implicit_exception_pc_offset())), (int32_t)NULL_WORD);
2827 
2828     uncommon_trap_offset = __ pc() - start;
2829 
2830     // Save everything in sight.
2831     RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
2832     // fetch_unroll_info needs to call last_java_frame()
2833     __ set_last_Java_frame(noreg, noreg, NULL);
2834 
2835     __ movl(c_rarg1, Address(r15_thread, in_bytes(JavaThread::pending_deoptimization_offset())));
2836     __ movl(Address(r15_thread, in_bytes(JavaThread::pending_deoptimization_offset())), -1);
2837 
2838     __ movl(r14, (int32_t)Deoptimization::Unpack_reexecute);
2839     __ mov(c_rarg0, r15_thread);
2840     __ movl(c_rarg2, r14); // exec mode
2841     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::uncommon_trap)));
2842     oop_maps->add_gc_map( __ pc()-start, map->deep_copy());
2843 
2844     __ reset_last_Java_frame(false, false);
2845 
2846     __ jmp(after_fetch_unroll_info_call);
2847   } // EnableJVMCI
2848 #endif // INCLUDE_JVMCI
2849 
2850   int exception_offset = __ pc() - start;
2851 
2852   // Prolog for exception case
2853 
2854   // all registers are dead at this entry point, except for rax, and
2855   // rdx which contain the exception oop and exception pc
2856   // respectively.  Set them in TLS and fall thru to the
2857   // unpack_with_exception_in_tls entry point.
2858 
2859   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), rdx);
2860   __ movptr(Address(r15_thread, JavaThread::exception_oop_offset()), rax);
2861 
2862   int exception_in_tls_offset = __ pc() - start;
2863 
2864   // new implementation because exception oop is now passed in JavaThread
2865 
2866   // Prolog for exception case
2867   // All registers must be preserved because they might be used by LinearScan
2868   // Exceptiop oop and throwing PC are passed in JavaThread
2869   // tos: stack at point of call to method that threw the exception (i.e. only
2870   // args are on the stack, no return address)
2871 
2872   // make room on stack for the return address
2873   // It will be patched later with the throwing pc. The correct value is not
2874   // available now because loading it from memory would destroy registers.
2875   __ push(0);
2876 
2877   // Save everything in sight.
2878   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
2879 
2880   // Now it is safe to overwrite any register
2881 
2882   // Deopt during an exception.  Save exec mode for unpack_frames.
2883   __ movl(r14, Deoptimization::Unpack_exception); // callee-saved
2884 
2885   // load throwing pc from JavaThread and patch it as the return address
2886   // of the current frame. Then clear the field in JavaThread
2887 
2888   __ movptr(rdx, Address(r15_thread, JavaThread::exception_pc_offset()));
2889   __ movptr(Address(rbp, wordSize), rdx);
2890   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), (int32_t)NULL_WORD);
2891 
2892 #ifdef ASSERT
2893   // verify that there is really an exception oop in JavaThread
2894   __ movptr(rax, Address(r15_thread, JavaThread::exception_oop_offset()));
2895   __ verify_oop(rax);
2896 
2897   // verify that there is no pending exception
2898   Label no_pending_exception;
2899   __ movptr(rax, Address(r15_thread, Thread::pending_exception_offset()));
2900   __ testptr(rax, rax);
2901   __ jcc(Assembler::zero, no_pending_exception);
2902   __ stop("must not have pending exception here");
2903   __ bind(no_pending_exception);
2904 #endif
2905 
2906   __ bind(cont);
2907 
2908   // Call C code.  Need thread and this frame, but NOT official VM entry
2909   // crud.  We cannot block on this call, no GC can happen.
2910   //
2911   // UnrollBlock* fetch_unroll_info(JavaThread* thread)
2912 
2913   // fetch_unroll_info needs to call last_java_frame().
2914 
2915   __ set_last_Java_frame(noreg, noreg, NULL);
2916 #ifdef ASSERT
2917   { Label L;
2918     __ cmpptr(Address(r15_thread,
2919                     JavaThread::last_Java_fp_offset()),
2920             (int32_t)0);
2921     __ jcc(Assembler::equal, L);
2922     __ stop("SharedRuntime::generate_deopt_blob: last_Java_fp not cleared");
2923     __ bind(L);
2924   }
2925 #endif // ASSERT
2926   __ mov(c_rarg0, r15_thread);
2927   __ movl(c_rarg1, r14); // exec_mode
2928   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::fetch_unroll_info)));
2929 
2930   // Need to have an oopmap that tells fetch_unroll_info where to
2931   // find any register it might need.
2932   oop_maps->add_gc_map(__ pc() - start, map);
2933 
2934   __ reset_last_Java_frame(false, false);
2935 
2936 #if INCLUDE_JVMCI
2937   if (EnableJVMCI) {
2938     __ bind(after_fetch_unroll_info_call);
2939   }
2940 #endif
2941 
2942   // Load UnrollBlock* into rdi
2943   __ mov(rdi, rax);
2944 
2945   __ movl(r14, Address(rdi, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes()));
2946    Label noException;
2947   __ cmpl(r14, Deoptimization::Unpack_exception);   // Was exception pending?
2948   __ jcc(Assembler::notEqual, noException);
2949   __ movptr(rax, Address(r15_thread, JavaThread::exception_oop_offset()));
2950   // QQQ this is useless it was NULL above
2951   __ movptr(rdx, Address(r15_thread, JavaThread::exception_pc_offset()));
2952   __ movptr(Address(r15_thread, JavaThread::exception_oop_offset()), (int32_t)NULL_WORD);
2953   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), (int32_t)NULL_WORD);
2954 
2955   __ verify_oop(rax);
2956 
2957   // Overwrite the result registers with the exception results.
2958   __ movptr(Address(rsp, RegisterSaver::rax_offset_in_bytes()), rax);
2959   // I think this is useless
2960   __ movptr(Address(rsp, RegisterSaver::rdx_offset_in_bytes()), rdx);
2961 
2962   __ bind(noException);
2963 
2964   // Only register save data is on the stack.
2965   // Now restore the result registers.  Everything else is either dead
2966   // or captured in the vframeArray.
2967   RegisterSaver::restore_result_registers(masm);
2968 
2969   // All of the register save area has been popped of the stack. Only the
2970   // return address remains.
2971 
2972   // Pop all the frames we must move/replace.
2973   //
2974   // Frame picture (youngest to oldest)
2975   // 1: self-frame (no frame link)
2976   // 2: deopting frame  (no frame link)
2977   // 3: caller of deopting frame (could be compiled/interpreted).
2978   //
2979   // Note: by leaving the return address of self-frame on the stack
2980   // and using the size of frame 2 to adjust the stack
2981   // when we are done the return to frame 3 will still be on the stack.
2982 
2983   // Pop deoptimized frame
2984   __ movl(rcx, Address(rdi, Deoptimization::UnrollBlock::size_of_deoptimized_frame_offset_in_bytes()));
2985   __ addptr(rsp, rcx);
2986 
2987   // rsp should be pointing at the return address to the caller (3)
2988 
2989   // Pick up the initial fp we should save
2990   // restore rbp before stack bang because if stack overflow is thrown it needs to be pushed (and preserved)
2991   __ movptr(rbp, Address(rdi, Deoptimization::UnrollBlock::initial_info_offset_in_bytes()));
2992 
2993 #ifdef ASSERT
2994   // Compilers generate code that bang the stack by as much as the
2995   // interpreter would need. So this stack banging should never
2996   // trigger a fault. Verify that it does not on non product builds.
2997   if (UseStackBanging) {
2998     __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes()));
2999     __ bang_stack_size(rbx, rcx);
3000   }
3001 #endif
3002 
3003   // Load address of array of frame pcs into rcx
3004   __ movptr(rcx, Address(rdi, Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
3005 
3006   // Trash the old pc
3007   __ addptr(rsp, wordSize);
3008 
3009   // Load address of array of frame sizes into rsi
3010   __ movptr(rsi, Address(rdi, Deoptimization::UnrollBlock::frame_sizes_offset_in_bytes()));
3011 
3012   // Load counter into rdx
3013   __ movl(rdx, Address(rdi, Deoptimization::UnrollBlock::number_of_frames_offset_in_bytes()));
3014 
3015   // Now adjust the caller's stack to make up for the extra locals
3016   // but record the original sp so that we can save it in the skeletal interpreter
3017   // frame and the stack walking of interpreter_sender will get the unextended sp
3018   // value and not the "real" sp value.
3019 
3020   const Register sender_sp = r8;
3021 
3022   __ mov(sender_sp, rsp);
3023   __ movl(rbx, Address(rdi,
3024                        Deoptimization::UnrollBlock::
3025                        caller_adjustment_offset_in_bytes()));
3026   __ subptr(rsp, rbx);
3027 
3028   // Push interpreter frames in a loop
3029   Label loop;
3030   __ bind(loop);
3031   __ movptr(rbx, Address(rsi, 0));      // Load frame size
3032   __ subptr(rbx, 2*wordSize);           // We'll push pc and ebp by hand
3033   __ pushptr(Address(rcx, 0));          // Save return address
3034   __ enter();                           // Save old & set new ebp
3035   __ subptr(rsp, rbx);                  // Prolog
3036   // This value is corrected by layout_activation_impl
3037   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), (int32_t)NULL_WORD );
3038   __ movptr(Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize), sender_sp); // Make it walkable
3039   __ mov(sender_sp, rsp);               // Pass sender_sp to next frame
3040   __ addptr(rsi, wordSize);             // Bump array pointer (sizes)
3041   __ addptr(rcx, wordSize);             // Bump array pointer (pcs)
3042   __ decrementl(rdx);                   // Decrement counter
3043   __ jcc(Assembler::notZero, loop);
3044   __ pushptr(Address(rcx, 0));          // Save final return address
3045 
3046   // Re-push self-frame
3047   __ enter();                           // Save old & set new ebp
3048 
3049   // Allocate a full sized register save area.
3050   // Return address and rbp are in place, so we allocate two less words.
3051   __ subptr(rsp, (frame_size_in_words - 2) * wordSize);
3052 
3053   // Restore frame locals after moving the frame
3054   __ movdbl(Address(rsp, RegisterSaver::xmm0_offset_in_bytes()), xmm0);
3055   __ movptr(Address(rsp, RegisterSaver::rax_offset_in_bytes()), rax);
3056 
3057   // Call C code.  Need thread but NOT official VM entry
3058   // crud.  We cannot block on this call, no GC can happen.  Call should
3059   // restore return values to their stack-slots with the new SP.
3060   //
3061   // void Deoptimization::unpack_frames(JavaThread* thread, int exec_mode)
3062 
3063   // Use rbp because the frames look interpreted now
3064   // Save "the_pc" since it cannot easily be retrieved using the last_java_SP after we aligned SP.
3065   // Don't need the precise return PC here, just precise enough to point into this code blob.
3066   address the_pc = __ pc();
3067   __ set_last_Java_frame(noreg, rbp, the_pc);
3068 
3069   __ andptr(rsp, -(StackAlignmentInBytes));  // Fix stack alignment as required by ABI
3070   __ mov(c_rarg0, r15_thread);
3071   __ movl(c_rarg1, r14); // second arg: exec_mode
3072   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
3073   // Revert SP alignment after call since we're going to do some SP relative addressing below
3074   __ movptr(rsp, Address(r15_thread, JavaThread::last_Java_sp_offset()));
3075 
3076   // Set an oopmap for the call site
3077   // Use the same PC we used for the last java frame
3078   oop_maps->add_gc_map(the_pc - start,
3079                        new OopMap( frame_size_in_words, 0 ));
3080 
3081   // Clear fp AND pc
3082   __ reset_last_Java_frame(true, true);
3083 
3084   // Collect return values
3085   __ movdbl(xmm0, Address(rsp, RegisterSaver::xmm0_offset_in_bytes()));
3086   __ movptr(rax, Address(rsp, RegisterSaver::rax_offset_in_bytes()));
3087   // I think this is useless (throwing pc?)
3088   __ movptr(rdx, Address(rsp, RegisterSaver::rdx_offset_in_bytes()));
3089 
3090   // Pop self-frame.
3091   __ leave();                           // Epilog
3092 
3093   // Jump to interpreter
3094   __ ret(0);
3095 
3096   // Make sure all code is generated
3097   masm->flush();
3098 
3099   _deopt_blob = DeoptimizationBlob::create(&buffer, oop_maps, 0, exception_offset, reexecute_offset, frame_size_in_words);
3100   _deopt_blob->set_unpack_with_exception_in_tls_offset(exception_in_tls_offset);
3101 #if INCLUDE_JVMCI
3102   if (EnableJVMCI) {
3103     _deopt_blob->set_uncommon_trap_offset(uncommon_trap_offset);
3104     _deopt_blob->set_implicit_exception_uncommon_trap_offset(implicit_exception_uncommon_trap_offset);
3105   }
3106 #endif
3107 }
3108 
3109 #ifdef COMPILER2
3110 //------------------------------generate_uncommon_trap_blob--------------------
3111 void SharedRuntime::generate_uncommon_trap_blob() {
3112   // Allocate space for the code
3113   ResourceMark rm;
3114   // Setup code generation tools
3115   CodeBuffer buffer("uncommon_trap_blob", 2048, 1024);
3116   MacroAssembler* masm = new MacroAssembler(&buffer);
3117 
3118   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
3119 
3120   address start = __ pc();
3121 
3122   if (UseRTMLocking) {
3123     // Abort RTM transaction before possible nmethod deoptimization.
3124     __ xabort(0);
3125   }
3126 
3127   // Push self-frame.  We get here with a return address on the
3128   // stack, so rsp is 8-byte aligned until we allocate our frame.
3129   __ subptr(rsp, SimpleRuntimeFrame::return_off << LogBytesPerInt); // Epilog!
3130 
3131   // No callee saved registers. rbp is assumed implicitly saved
3132   __ movptr(Address(rsp, SimpleRuntimeFrame::rbp_off << LogBytesPerInt), rbp);
3133 
3134   // compiler left unloaded_class_index in j_rarg0 move to where the
3135   // runtime expects it.
3136   __ movl(c_rarg1, j_rarg0);
3137 
3138   __ set_last_Java_frame(noreg, noreg, NULL);
3139 
3140   // Call C code.  Need thread but NOT official VM entry
3141   // crud.  We cannot block on this call, no GC can happen.  Call should
3142   // capture callee-saved registers as well as return values.
3143   // Thread is in rdi already.
3144   //
3145   // UnrollBlock* uncommon_trap(JavaThread* thread, jint unloaded_class_index);
3146 
3147   __ mov(c_rarg0, r15_thread);
3148   __ movl(c_rarg2, Deoptimization::Unpack_uncommon_trap);
3149   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::uncommon_trap)));
3150 
3151   // Set an oopmap for the call site
3152   OopMapSet* oop_maps = new OopMapSet();
3153   OopMap* map = new OopMap(SimpleRuntimeFrame::framesize, 0);
3154 
3155   // location of rbp is known implicitly by the frame sender code
3156 
3157   oop_maps->add_gc_map(__ pc() - start, map);
3158 
3159   __ reset_last_Java_frame(false, false);
3160 
3161   // Load UnrollBlock* into rdi
3162   __ mov(rdi, rax);
3163 
3164 #ifdef ASSERT
3165   { Label L;
3166     __ cmpptr(Address(rdi, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes()),
3167             (int32_t)Deoptimization::Unpack_uncommon_trap);
3168     __ jcc(Assembler::equal, L);
3169     __ stop("SharedRuntime::generate_deopt_blob: expected Unpack_uncommon_trap");
3170     __ bind(L);
3171   }
3172 #endif
3173 
3174   // Pop all the frames we must move/replace.
3175   //
3176   // Frame picture (youngest to oldest)
3177   // 1: self-frame (no frame link)
3178   // 2: deopting frame  (no frame link)
3179   // 3: caller of deopting frame (could be compiled/interpreted).
3180 
3181   // Pop self-frame.  We have no frame, and must rely only on rax and rsp.
3182   __ addptr(rsp, (SimpleRuntimeFrame::framesize - 2) << LogBytesPerInt); // Epilog!
3183 
3184   // Pop deoptimized frame (int)
3185   __ movl(rcx, Address(rdi,
3186                        Deoptimization::UnrollBlock::
3187                        size_of_deoptimized_frame_offset_in_bytes()));
3188   __ addptr(rsp, rcx);
3189 
3190   // rsp should be pointing at the return address to the caller (3)
3191 
3192   // Pick up the initial fp we should save
3193   // restore rbp before stack bang because if stack overflow is thrown it needs to be pushed (and preserved)
3194   __ movptr(rbp, Address(rdi, Deoptimization::UnrollBlock::initial_info_offset_in_bytes()));
3195 
3196 #ifdef ASSERT
3197   // Compilers generate code that bang the stack by as much as the
3198   // interpreter would need. So this stack banging should never
3199   // trigger a fault. Verify that it does not on non product builds.
3200   if (UseStackBanging) {
3201     __ movl(rbx, Address(rdi ,Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes()));
3202     __ bang_stack_size(rbx, rcx);
3203   }
3204 #endif
3205 
3206   // Load address of array of frame pcs into rcx (address*)
3207   __ movptr(rcx, Address(rdi, Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
3208 
3209   // Trash the return pc
3210   __ addptr(rsp, wordSize);
3211 
3212   // Load address of array of frame sizes into rsi (intptr_t*)
3213   __ movptr(rsi, Address(rdi, Deoptimization::UnrollBlock:: frame_sizes_offset_in_bytes()));
3214 
3215   // Counter
3216   __ movl(rdx, Address(rdi, Deoptimization::UnrollBlock:: number_of_frames_offset_in_bytes())); // (int)
3217 
3218   // Now adjust the caller's stack to make up for the extra locals but
3219   // record the original sp so that we can save it in the skeletal
3220   // interpreter frame and the stack walking of interpreter_sender
3221   // will get the unextended sp value and not the "real" sp value.
3222 
3223   const Register sender_sp = r8;
3224 
3225   __ mov(sender_sp, rsp);
3226   __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock:: caller_adjustment_offset_in_bytes())); // (int)
3227   __ subptr(rsp, rbx);
3228 
3229   // Push interpreter frames in a loop
3230   Label loop;
3231   __ bind(loop);
3232   __ movptr(rbx, Address(rsi, 0)); // Load frame size
3233   __ subptr(rbx, 2 * wordSize);    // We'll push pc and rbp by hand
3234   __ pushptr(Address(rcx, 0));     // Save return address
3235   __ enter();                      // Save old & set new rbp
3236   __ subptr(rsp, rbx);             // Prolog
3237   __ movptr(Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize),
3238             sender_sp);            // Make it walkable
3239   // This value is corrected by layout_activation_impl
3240   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), (int32_t)NULL_WORD );
3241   __ mov(sender_sp, rsp);          // Pass sender_sp to next frame
3242   __ addptr(rsi, wordSize);        // Bump array pointer (sizes)
3243   __ addptr(rcx, wordSize);        // Bump array pointer (pcs)
3244   __ decrementl(rdx);              // Decrement counter
3245   __ jcc(Assembler::notZero, loop);
3246   __ pushptr(Address(rcx, 0));     // Save final return address
3247 
3248   // Re-push self-frame
3249   __ enter();                 // Save old & set new rbp
3250   __ subptr(rsp, (SimpleRuntimeFrame::framesize - 4) << LogBytesPerInt);
3251                               // Prolog
3252 
3253   // Use rbp because the frames look interpreted now
3254   // Save "the_pc" since it cannot easily be retrieved using the last_java_SP after we aligned SP.
3255   // Don't need the precise return PC here, just precise enough to point into this code blob.
3256   address the_pc = __ pc();
3257   __ set_last_Java_frame(noreg, rbp, the_pc);
3258 
3259   // Call C code.  Need thread but NOT official VM entry
3260   // crud.  We cannot block on this call, no GC can happen.  Call should
3261   // restore return values to their stack-slots with the new SP.
3262   // Thread is in rdi already.
3263   //
3264   // BasicType unpack_frames(JavaThread* thread, int exec_mode);
3265 
3266   __ andptr(rsp, -(StackAlignmentInBytes)); // Align SP as required by ABI
3267   __ mov(c_rarg0, r15_thread);
3268   __ movl(c_rarg1, Deoptimization::Unpack_uncommon_trap);
3269   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
3270 
3271   // Set an oopmap for the call site
3272   // Use the same PC we used for the last java frame
3273   oop_maps->add_gc_map(the_pc - start, new OopMap(SimpleRuntimeFrame::framesize, 0));
3274 
3275   // Clear fp AND pc
3276   __ reset_last_Java_frame(true, true);
3277 
3278   // Pop self-frame.
3279   __ leave();                 // Epilog
3280 
3281   // Jump to interpreter
3282   __ ret(0);
3283 
3284   // Make sure all code is generated
3285   masm->flush();
3286 
3287   _uncommon_trap_blob =  UncommonTrapBlob::create(&buffer, oop_maps,
3288                                                  SimpleRuntimeFrame::framesize >> 1);
3289 }
3290 #endif // COMPILER2
3291 
3292 
3293 //------------------------------generate_handler_blob------
3294 //
3295 // Generate a special Compile2Runtime blob that saves all registers,
3296 // and setup oopmap.
3297 //
3298 SafepointBlob* SharedRuntime::generate_handler_blob(address call_ptr, int poll_type) {
3299   assert(StubRoutines::forward_exception_entry() != NULL,
3300          "must be generated before");
3301 
3302   ResourceMark rm;
3303   OopMapSet *oop_maps = new OopMapSet();
3304   OopMap* map;
3305 
3306   // Allocate space for the code.  Setup code generation tools.
3307   CodeBuffer buffer("handler_blob", 2048, 1024);
3308   MacroAssembler* masm = new MacroAssembler(&buffer);
3309 
3310   address start   = __ pc();
3311   address call_pc = NULL;
3312   int frame_size_in_words;
3313   bool cause_return = (poll_type == POLL_AT_RETURN);
3314   bool save_vectors = (poll_type == POLL_AT_VECTOR_LOOP);
3315 
3316   if (UseRTMLocking) {
3317     // Abort RTM transaction before calling runtime
3318     // because critical section will be large and will be
3319     // aborted anyway. Also nmethod could be deoptimized.
3320     __ xabort(0);
3321   }
3322 
3323   // Make room for return address (or push it again)
3324   if (!cause_return) {
3325     __ push(rbx);
3326   }
3327 
3328   // Save registers, fpu state, and flags
3329   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words, save_vectors);
3330 
3331   // The following is basically a call_VM.  However, we need the precise
3332   // address of the call in order to generate an oopmap. Hence, we do all the
3333   // work outselves.
3334 
3335   __ set_last_Java_frame(noreg, noreg, NULL);
3336 
3337   // The return address must always be correct so that frame constructor never
3338   // sees an invalid pc.
3339 
3340   if (!cause_return) {
3341     // overwrite the dummy value we pushed on entry
3342     __ movptr(c_rarg0, Address(r15_thread, JavaThread::saved_exception_pc_offset()));
3343     __ movptr(Address(rbp, wordSize), c_rarg0);
3344   }
3345 
3346   // Do the call
3347   __ mov(c_rarg0, r15_thread);
3348   __ call(RuntimeAddress(call_ptr));
3349 
3350   // Set an oopmap for the call site.  This oopmap will map all
3351   // oop-registers and debug-info registers as callee-saved.  This
3352   // will allow deoptimization at this safepoint to find all possible
3353   // debug-info recordings, as well as let GC find all oops.
3354 
3355   oop_maps->add_gc_map( __ pc() - start, map);
3356 
3357   Label noException;
3358 
3359   __ reset_last_Java_frame(false, false);
3360 
3361   __ cmpptr(Address(r15_thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
3362   __ jcc(Assembler::equal, noException);
3363 
3364   // Exception pending
3365 
3366   RegisterSaver::restore_live_registers(masm, save_vectors);
3367 
3368   __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3369 
3370   // No exception case
3371   __ bind(noException);
3372 
3373   // Normal exit, restore registers and exit.
3374   RegisterSaver::restore_live_registers(masm, save_vectors);
3375 
3376   __ ret(0);
3377 
3378   // Make sure all code is generated
3379   masm->flush();
3380 
3381   // Fill-out other meta info
3382   return SafepointBlob::create(&buffer, oop_maps, frame_size_in_words);
3383 }
3384 
3385 //
3386 // generate_resolve_blob - call resolution (static/virtual/opt-virtual/ic-miss
3387 //
3388 // Generate a stub that calls into vm to find out the proper destination
3389 // of a java call. All the argument registers are live at this point
3390 // but since this is generic code we don't know what they are and the caller
3391 // must do any gc of the args.
3392 //
3393 RuntimeStub* SharedRuntime::generate_resolve_blob(address destination, const char* name) {
3394   assert (StubRoutines::forward_exception_entry() != NULL, "must be generated before");
3395 
3396   // allocate space for the code
3397   ResourceMark rm;
3398 
3399   CodeBuffer buffer(name, 1000, 512);
3400   MacroAssembler* masm                = new MacroAssembler(&buffer);
3401 
3402   int frame_size_in_words;
3403 
3404   OopMapSet *oop_maps = new OopMapSet();
3405   OopMap* map = NULL;
3406 
3407   int start = __ offset();
3408 
3409   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
3410 
3411   int frame_complete = __ offset();
3412 
3413   __ set_last_Java_frame(noreg, noreg, NULL);
3414 
3415   __ mov(c_rarg0, r15_thread);
3416 
3417   __ call(RuntimeAddress(destination));
3418 
3419 
3420   // Set an oopmap for the call site.
3421   // We need this not only for callee-saved registers, but also for volatile
3422   // registers that the compiler might be keeping live across a safepoint.
3423 
3424   oop_maps->add_gc_map( __ offset() - start, map);
3425 
3426   // rax contains the address we are going to jump to assuming no exception got installed
3427 
3428   // clear last_Java_sp
3429   __ reset_last_Java_frame(false, false);
3430   // check for pending exceptions
3431   Label pending;
3432   __ cmpptr(Address(r15_thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
3433   __ jcc(Assembler::notEqual, pending);
3434 
3435   // get the returned Method*
3436   __ get_vm_result_2(rbx, r15_thread);
3437   __ movptr(Address(rsp, RegisterSaver::rbx_offset_in_bytes()), rbx);
3438 
3439   __ movptr(Address(rsp, RegisterSaver::rax_offset_in_bytes()), rax);
3440 
3441   RegisterSaver::restore_live_registers(masm);
3442 
3443   // We are back the the original state on entry and ready to go.
3444 
3445   __ jmp(rax);
3446 
3447   // Pending exception after the safepoint
3448 
3449   __ bind(pending);
3450 
3451   RegisterSaver::restore_live_registers(masm);
3452 
3453   // exception pending => remove activation and forward to exception handler
3454 
3455   __ movptr(Address(r15_thread, JavaThread::vm_result_offset()), (int)NULL_WORD);
3456 
3457   __ movptr(rax, Address(r15_thread, Thread::pending_exception_offset()));
3458   __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3459 
3460   // -------------
3461   // make sure all code is generated
3462   masm->flush();
3463 
3464   // return the  blob
3465   // frame_size_words or bytes??
3466   return RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, frame_size_in_words, oop_maps, true);
3467 }
3468 
3469 
3470 //------------------------------Montgomery multiplication------------------------
3471 //
3472 
3473 #ifndef _WINDOWS
3474 
3475 #define ASM_SUBTRACT
3476 
3477 #ifdef ASM_SUBTRACT
3478 // Subtract 0:b from carry:a.  Return carry.
3479 static unsigned long
3480 sub(unsigned long a[], unsigned long b[], unsigned long carry, long len) {
3481   long i = 0, cnt = len;
3482   unsigned long tmp;
3483   asm volatile("clc; "
3484                "0: ; "
3485                "mov (%[b], %[i], 8), %[tmp]; "
3486                "sbb %[tmp], (%[a], %[i], 8); "
3487                "inc %[i]; dec %[cnt]; "
3488                "jne 0b; "
3489                "mov %[carry], %[tmp]; sbb $0, %[tmp]; "
3490                : [i]"+r"(i), [cnt]"+r"(cnt), [tmp]"=&r"(tmp)
3491                : [a]"r"(a), [b]"r"(b), [carry]"r"(carry)
3492                : "memory");
3493   return tmp;
3494 }
3495 #else // ASM_SUBTRACT
3496 typedef int __attribute__((mode(TI))) int128;
3497 
3498 // Subtract 0:b from carry:a.  Return carry.
3499 static unsigned long
3500 sub(unsigned long a[], unsigned long b[], unsigned long carry, int len) {
3501   int128 tmp = 0;
3502   int i;
3503   for (i = 0; i < len; i++) {
3504     tmp += a[i];
3505     tmp -= b[i];
3506     a[i] = tmp;
3507     tmp >>= 64;
3508     assert(-1 <= tmp && tmp <= 0, "invariant");
3509   }
3510   return tmp + carry;
3511 }
3512 #endif // ! ASM_SUBTRACT
3513 
3514 // Multiply (unsigned) Long A by Long B, accumulating the double-
3515 // length result into the accumulator formed of T0, T1, and T2.
3516 #define MACC(A, B, T0, T1, T2)                                  \
3517 do {                                                            \
3518   unsigned long hi, lo;                                         \
3519   __asm__ ("mul %5; add %%rax, %2; adc %%rdx, %3; adc $0, %4"   \
3520            : "=&d"(hi), "=a"(lo), "+r"(T0), "+r"(T1), "+g"(T2)  \
3521            : "r"(A), "a"(B) : "cc");                            \
3522  } while(0)
3523 
3524 // As above, but add twice the double-length result into the
3525 // accumulator.
3526 #define MACC2(A, B, T0, T1, T2)                                 \
3527 do {                                                            \
3528   unsigned long hi, lo;                                         \
3529   __asm__ ("mul %5; add %%rax, %2; adc %%rdx, %3; adc $0, %4; " \
3530            "add %%rax, %2; adc %%rdx, %3; adc $0, %4"           \
3531            : "=&d"(hi), "=a"(lo), "+r"(T0), "+r"(T1), "+g"(T2)  \
3532            : "r"(A), "a"(B) : "cc");                            \
3533  } while(0)
3534 
3535 // Fast Montgomery multiplication.  The derivation of the algorithm is
3536 // in  A Cryptographic Library for the Motorola DSP56000,
3537 // Dusse and Kaliski, Proc. EUROCRYPT 90, pp. 230-237.
3538 
3539 static void __attribute__((noinline))
3540 montgomery_multiply(unsigned long a[], unsigned long b[], unsigned long n[],
3541                     unsigned long m[], unsigned long inv, int len) {
3542   unsigned long t0 = 0, t1 = 0, t2 = 0; // Triple-precision accumulator
3543   int i;
3544 
3545   assert(inv * n[0] == -1UL, "broken inverse in Montgomery multiply");
3546 
3547   for (i = 0; i < len; i++) {
3548     int j;
3549     for (j = 0; j < i; j++) {
3550       MACC(a[j], b[i-j], t0, t1, t2);
3551       MACC(m[j], n[i-j], t0, t1, t2);
3552     }
3553     MACC(a[i], b[0], t0, t1, t2);
3554     m[i] = t0 * inv;
3555     MACC(m[i], n[0], t0, t1, t2);
3556 
3557     assert(t0 == 0, "broken Montgomery multiply");
3558 
3559     t0 = t1; t1 = t2; t2 = 0;
3560   }
3561 
3562   for (i = len; i < 2*len; i++) {
3563     int j;
3564     for (j = i-len+1; j < len; j++) {
3565       MACC(a[j], b[i-j], t0, t1, t2);
3566       MACC(m[j], n[i-j], t0, t1, t2);
3567     }
3568     m[i-len] = t0;
3569     t0 = t1; t1 = t2; t2 = 0;
3570   }
3571 
3572   while (t0)
3573     t0 = sub(m, n, t0, len);
3574 }
3575 
3576 // Fast Montgomery squaring.  This uses asymptotically 25% fewer
3577 // multiplies so it should be up to 25% faster than Montgomery
3578 // multiplication.  However, its loop control is more complex and it
3579 // may actually run slower on some machines.
3580 
3581 static void __attribute__((noinline))
3582 montgomery_square(unsigned long a[], unsigned long n[],
3583                   unsigned long m[], unsigned long inv, int len) {
3584   unsigned long t0 = 0, t1 = 0, t2 = 0; // Triple-precision accumulator
3585   int i;
3586 
3587   assert(inv * n[0] == -1UL, "broken inverse in Montgomery multiply");
3588 
3589   for (i = 0; i < len; i++) {
3590     int j;
3591     int end = (i+1)/2;
3592     for (j = 0; j < end; j++) {
3593       MACC2(a[j], a[i-j], t0, t1, t2);
3594       MACC(m[j], n[i-j], t0, t1, t2);
3595     }
3596     if ((i & 1) == 0) {
3597       MACC(a[j], a[j], t0, t1, t2);
3598     }
3599     for (; j < i; j++) {
3600       MACC(m[j], n[i-j], t0, t1, t2);
3601     }
3602     m[i] = t0 * inv;
3603     MACC(m[i], n[0], t0, t1, t2);
3604 
3605     assert(t0 == 0, "broken Montgomery square");
3606 
3607     t0 = t1; t1 = t2; t2 = 0;
3608   }
3609 
3610   for (i = len; i < 2*len; i++) {
3611     int start = i-len+1;
3612     int end = start + (len - start)/2;
3613     int j;
3614     for (j = start; j < end; j++) {
3615       MACC2(a[j], a[i-j], t0, t1, t2);
3616       MACC(m[j], n[i-j], t0, t1, t2);
3617     }
3618     if ((i & 1) == 0) {
3619       MACC(a[j], a[j], t0, t1, t2);
3620     }
3621     for (; j < len; j++) {
3622       MACC(m[j], n[i-j], t0, t1, t2);
3623     }
3624     m[i-len] = t0;
3625     t0 = t1; t1 = t2; t2 = 0;
3626   }
3627 
3628   while (t0)
3629     t0 = sub(m, n, t0, len);
3630 }
3631 
3632 // Swap words in a longword.
3633 static unsigned long swap(unsigned long x) {
3634   return (x << 32) | (x >> 32);
3635 }
3636 
3637 // Copy len longwords from s to d, word-swapping as we go.  The
3638 // destination array is reversed.
3639 static void reverse_words(unsigned long *s, unsigned long *d, int len) {
3640   d += len;
3641   while(len-- > 0) {
3642     d--;
3643     *d = swap(*s);
3644     s++;
3645   }
3646 }
3647 
3648 // The threshold at which squaring is advantageous was determined
3649 // experimentally on an i7-3930K (Ivy Bridge) CPU @ 3.5GHz.
3650 #define MONTGOMERY_SQUARING_THRESHOLD 64
3651 
3652 void SharedRuntime::montgomery_multiply(jint *a_ints, jint *b_ints, jint *n_ints,
3653                                         jint len, jlong inv,
3654                                         jint *m_ints) {
3655   assert(len % 2 == 0, "array length in montgomery_multiply must be even");
3656   int longwords = len/2;
3657 
3658   // Make very sure we don't use so much space that the stack might
3659   // overflow.  512 jints corresponds to an 16384-bit integer and
3660   // will use here a total of 8k bytes of stack space.
3661   int total_allocation = longwords * sizeof (unsigned long) * 4;
3662   guarantee(total_allocation <= 8192, "must be");
3663   unsigned long *scratch = (unsigned long *)alloca(total_allocation);
3664 
3665   // Local scratch arrays
3666   unsigned long
3667     *a = scratch + 0 * longwords,
3668     *b = scratch + 1 * longwords,
3669     *n = scratch + 2 * longwords,
3670     *m = scratch + 3 * longwords;
3671 
3672   reverse_words((unsigned long *)a_ints, a, longwords);
3673   reverse_words((unsigned long *)b_ints, b, longwords);
3674   reverse_words((unsigned long *)n_ints, n, longwords);
3675 
3676   ::montgomery_multiply(a, b, n, m, (unsigned long)inv, longwords);
3677 
3678   reverse_words(m, (unsigned long *)m_ints, longwords);
3679 }
3680 
3681 void SharedRuntime::montgomery_square(jint *a_ints, jint *n_ints,
3682                                       jint len, jlong inv,
3683                                       jint *m_ints) {
3684   assert(len % 2 == 0, "array length in montgomery_square must be even");
3685   int longwords = len/2;
3686 
3687   // Make very sure we don't use so much space that the stack might
3688   // overflow.  512 jints corresponds to an 16384-bit integer and
3689   // will use here a total of 6k bytes of stack space.
3690   int total_allocation = longwords * sizeof (unsigned long) * 3;
3691   guarantee(total_allocation <= 8192, "must be");
3692   unsigned long *scratch = (unsigned long *)alloca(total_allocation);
3693 
3694   // Local scratch arrays
3695   unsigned long
3696     *a = scratch + 0 * longwords,
3697     *n = scratch + 1 * longwords,
3698     *m = scratch + 2 * longwords;
3699 
3700   reverse_words((unsigned long *)a_ints, a, longwords);
3701   reverse_words((unsigned long *)n_ints, n, longwords);
3702 
3703   if (len >= MONTGOMERY_SQUARING_THRESHOLD) {
3704     ::montgomery_square(a, n, m, (unsigned long)inv, longwords);
3705   } else {
3706     ::montgomery_multiply(a, a, n, m, (unsigned long)inv, longwords);
3707   }
3708 
3709   reverse_words(m, (unsigned long *)m_ints, longwords);
3710 }
3711 
3712 #endif // WINDOWS
3713 
3714 #ifdef COMPILER2
3715 // This is here instead of runtime_x86_64.cpp because it uses SimpleRuntimeFrame
3716 //
3717 //------------------------------generate_exception_blob---------------------------
3718 // creates exception blob at the end
3719 // Using exception blob, this code is jumped from a compiled method.
3720 // (see emit_exception_handler in x86_64.ad file)
3721 //
3722 // Given an exception pc at a call we call into the runtime for the
3723 // handler in this method. This handler might merely restore state
3724 // (i.e. callee save registers) unwind the frame and jump to the
3725 // exception handler for the nmethod if there is no Java level handler
3726 // for the nmethod.
3727 //
3728 // This code is entered with a jmp.
3729 //
3730 // Arguments:
3731 //   rax: exception oop
3732 //   rdx: exception pc
3733 //
3734 // Results:
3735 //   rax: exception oop
3736 //   rdx: exception pc in caller or ???
3737 //   destination: exception handler of caller
3738 //
3739 // Note: the exception pc MUST be at a call (precise debug information)
3740 //       Registers rax, rdx, rcx, rsi, rdi, r8-r11 are not callee saved.
3741 //
3742 
3743 void OptoRuntime::generate_exception_blob() {
3744   assert(!OptoRuntime::is_callee_saved_register(RDX_num), "");
3745   assert(!OptoRuntime::is_callee_saved_register(RAX_num), "");
3746   assert(!OptoRuntime::is_callee_saved_register(RCX_num), "");
3747 
3748   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
3749 
3750   // Allocate space for the code
3751   ResourceMark rm;
3752   // Setup code generation tools
3753   CodeBuffer buffer("exception_blob", 2048, 1024);
3754   MacroAssembler* masm = new MacroAssembler(&buffer);
3755 
3756 
3757   address start = __ pc();
3758 
3759   // Exception pc is 'return address' for stack walker
3760   __ push(rdx);
3761   __ subptr(rsp, SimpleRuntimeFrame::return_off << LogBytesPerInt); // Prolog
3762 
3763   // Save callee-saved registers.  See x86_64.ad.
3764 
3765   // rbp is an implicitly saved callee saved register (i.e., the calling
3766   // convention will save/restore it in the prolog/epilog). Other than that
3767   // there are no callee save registers now that adapter frames are gone.
3768 
3769   __ movptr(Address(rsp, SimpleRuntimeFrame::rbp_off << LogBytesPerInt), rbp);
3770 
3771   // Store exception in Thread object. We cannot pass any arguments to the
3772   // handle_exception call, since we do not want to make any assumption
3773   // about the size of the frame where the exception happened in.
3774   // c_rarg0 is either rdi (Linux) or rcx (Windows).
3775   __ movptr(Address(r15_thread, JavaThread::exception_oop_offset()),rax);
3776   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), rdx);
3777 
3778   // This call does all the hard work.  It checks if an exception handler
3779   // exists in the method.
3780   // If so, it returns the handler address.
3781   // If not, it prepares for stack-unwinding, restoring the callee-save
3782   // registers of the frame being removed.
3783   //
3784   // address OptoRuntime::handle_exception_C(JavaThread* thread)
3785 
3786   // At a method handle call, the stack may not be properly aligned
3787   // when returning with an exception.
3788   address the_pc = __ pc();
3789   __ set_last_Java_frame(noreg, noreg, the_pc);
3790   __ mov(c_rarg0, r15_thread);
3791   __ andptr(rsp, -(StackAlignmentInBytes));    // Align stack
3792   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, OptoRuntime::handle_exception_C)));
3793 
3794   // Set an oopmap for the call site.  This oopmap will only be used if we
3795   // are unwinding the stack.  Hence, all locations will be dead.
3796   // Callee-saved registers will be the same as the frame above (i.e.,
3797   // handle_exception_stub), since they were restored when we got the
3798   // exception.
3799 
3800   OopMapSet* oop_maps = new OopMapSet();
3801 
3802   oop_maps->add_gc_map(the_pc - start, new OopMap(SimpleRuntimeFrame::framesize, 0));
3803 
3804   __ reset_last_Java_frame(false, true);
3805 
3806   // Restore callee-saved registers
3807 
3808   // rbp is an implicitly saved callee-saved register (i.e., the calling
3809   // convention will save restore it in prolog/epilog) Other than that
3810   // there are no callee save registers now that adapter frames are gone.
3811 
3812   __ movptr(rbp, Address(rsp, SimpleRuntimeFrame::rbp_off << LogBytesPerInt));
3813 
3814   __ addptr(rsp, SimpleRuntimeFrame::return_off << LogBytesPerInt); // Epilog
3815   __ pop(rdx);                  // No need for exception pc anymore
3816 
3817   // rax: exception handler
3818 
3819   // We have a handler in rax (could be deopt blob).
3820   __ mov(r8, rax);
3821 
3822   // Get the exception oop
3823   __ movptr(rax, Address(r15_thread, JavaThread::exception_oop_offset()));
3824   // Get the exception pc in case we are deoptimized
3825   __ movptr(rdx, Address(r15_thread, JavaThread::exception_pc_offset()));
3826 #ifdef ASSERT
3827   __ movptr(Address(r15_thread, JavaThread::exception_handler_pc_offset()), (int)NULL_WORD);
3828   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), (int)NULL_WORD);
3829 #endif
3830   // Clear the exception oop so GC no longer processes it as a root.
3831   __ movptr(Address(r15_thread, JavaThread::exception_oop_offset()), (int)NULL_WORD);
3832 
3833   // rax: exception oop
3834   // r8:  exception handler
3835   // rdx: exception pc
3836   // Jump to handler
3837 
3838   __ jmp(r8);
3839 
3840   // Make sure all code is generated
3841   masm->flush();
3842 
3843   // Set exception blob
3844   _exception_blob =  ExceptionBlob::create(&buffer, oop_maps, SimpleRuntimeFrame::framesize >> 1);
3845 }
3846 #endif // COMPILER2