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