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