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