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