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