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