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