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