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