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