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