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