1 /*
   2  * Copyright (c) 2003, 2020, 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 #include "asm/macroAssembler.hpp"
  27 #include "asm/macroAssembler.inline.hpp"
  28 #include "code/debugInfoRec.hpp"
  29 #include "code/icBuffer.hpp"
  30 #include "code/nativeInst.hpp"
  31 #include "code/vtableStubs.hpp"
  32 #include "gc/shared/gcLocker.hpp"
  33 #include "interpreter/interpreter.hpp"
  34 #include "logging/log.hpp"
  35 #include "memory/resourceArea.hpp"
  36 #include "oops/compiledICHolder.hpp"
  37 #include "runtime/safepointMechanism.hpp"
  38 #include "runtime/sharedRuntime.hpp"
  39 #include "runtime/vframeArray.hpp"
  40 #include "runtime/vm_version.hpp"
  41 #include "utilities/align.hpp"
  42 #include "utilities/macros.hpp"
  43 #include "vmreg_x86.inline.hpp"
  44 #ifdef COMPILER1
  45 #include "c1/c1_Runtime1.hpp"
  46 #endif
  47 #ifdef COMPILER2
  48 #include "opto/runtime.hpp"
  49 #endif
  50 #if INCLUDE_SHENANDOAHGC
  51 #include "gc/shenandoah/shenandoahBarrierSet.hpp"
  52 #include "gc/shenandoah/shenandoahBarrierSetAssembler.hpp"
  53 #endif
  54 
  55 #define __ masm->
  56 
  57 const int StackAlignmentInSlots = StackAlignmentInBytes / VMRegImpl::stack_slot_size;
  58 
  59 class RegisterSaver {
  60   // Capture info about frame layout
  61 #define DEF_XMM_OFFS(regnum) xmm ## regnum ## _off = xmm_off + (regnum)*16/BytesPerInt, xmm ## regnum ## H_off
  62   enum layout {
  63                 fpu_state_off = 0,
  64                 fpu_state_end = fpu_state_off+FPUStateSizeInWords,
  65                 st0_off, st0H_off,
  66                 st1_off, st1H_off,
  67                 st2_off, st2H_off,
  68                 st3_off, st3H_off,
  69                 st4_off, st4H_off,
  70                 st5_off, st5H_off,
  71                 st6_off, st6H_off,
  72                 st7_off, st7H_off,
  73                 xmm_off,
  74                 DEF_XMM_OFFS(0),
  75                 DEF_XMM_OFFS(1),
  76                 DEF_XMM_OFFS(2),
  77                 DEF_XMM_OFFS(3),
  78                 DEF_XMM_OFFS(4),
  79                 DEF_XMM_OFFS(5),
  80                 DEF_XMM_OFFS(6),
  81                 DEF_XMM_OFFS(7),
  82                 flags_off = xmm7_off + 16/BytesPerInt + 1, // 16-byte stack alignment fill word
  83                 rdi_off,
  84                 rsi_off,
  85                 ignore_off,  // extra copy of rbp,
  86                 rsp_off,
  87                 rbx_off,
  88                 rdx_off,
  89                 rcx_off,
  90                 rax_off,
  91                 // The frame sender code expects that rbp will be in the "natural" place and
  92                 // will override any oopMap setting for it. We must therefore force the layout
  93                 // so that it agrees with the frame sender code.
  94                 rbp_off,
  95                 return_off,      // slot for return address
  96                 reg_save_size };
  97   enum { FPU_regs_live = flags_off - fpu_state_end };
  98 
  99   public:
 100 
 101   static OopMap* save_live_registers(MacroAssembler* masm, int additional_frame_words,
 102                                      int* total_frame_words, bool verify_fpu = true, bool save_vectors = false);
 103   static void restore_live_registers(MacroAssembler* masm, bool restore_vectors = false);
 104 
 105   static int rax_offset() { return rax_off; }
 106   static int rbx_offset() { return rbx_off; }
 107 
 108   // Offsets into the register save area
 109   // Used by deoptimization when it is managing result register
 110   // values on its own
 111 
 112   static int raxOffset(void) { return rax_off; }
 113   static int rdxOffset(void) { return rdx_off; }
 114   static int rbxOffset(void) { return rbx_off; }
 115   static int xmm0Offset(void) { return xmm0_off; }
 116   // This really returns a slot in the fp save area, which one is not important
 117   static int fpResultOffset(void) { return st0_off; }
 118 
 119   // During deoptimization only the result register need to be restored
 120   // all the other values have already been extracted.
 121 
 122   static void restore_result_registers(MacroAssembler* masm);
 123 
 124 };
 125 
 126 OopMap* RegisterSaver::save_live_registers(MacroAssembler* masm, int additional_frame_words,
 127                                            int* total_frame_words, bool verify_fpu, bool save_vectors) {
 128   int num_xmm_regs = XMMRegisterImpl::number_of_registers;
 129   int ymm_bytes = num_xmm_regs * 16;
 130   int zmm_bytes = num_xmm_regs * 32;
 131 #ifdef COMPILER2
 132   if (save_vectors) {
 133     assert(UseAVX > 0, "Vectors larger than 16 byte long are supported only with AVX");
 134     assert(MaxVectorSize <= 64, "Only up to 64 byte long vectors are supported");
 135     // Save upper half of YMM registers
 136     int vect_bytes = ymm_bytes;
 137     if (UseAVX > 2) {
 138       // Save upper half of ZMM registers as well
 139       vect_bytes += zmm_bytes;
 140     }
 141     additional_frame_words += vect_bytes / wordSize;
 142   }
 143 #else
 144   assert(!save_vectors, "vectors are generated only by C2");
 145 #endif
 146   int frame_size_in_bytes = (reg_save_size + additional_frame_words) * wordSize;
 147   int frame_words = frame_size_in_bytes / wordSize;
 148   *total_frame_words = frame_words;
 149 
 150   assert(FPUStateSizeInWords == 27, "update stack layout");
 151 
 152   // save registers, fpu state, and flags
 153   // We assume caller has already has return address slot on the stack
 154   // We push epb twice in this sequence because we want the real rbp,
 155   // to be under the return like a normal enter and we want to use pusha
 156   // We push by hand instead of using push.
 157   __ enter();
 158   __ pusha();
 159   __ pushf();
 160   __ subptr(rsp,FPU_regs_live*wordSize); // Push FPU registers space
 161   __ push_FPU_state();          // Save FPU state & init
 162 
 163   if (verify_fpu) {
 164     // Some stubs may have non standard FPU control word settings so
 165     // only check and reset the value when it required to be the
 166     // standard value.  The safepoint blob in particular can be used
 167     // in methods which are using the 24 bit control word for
 168     // optimized float math.
 169 
 170 #ifdef ASSERT
 171     // Make sure the control word has the expected value
 172     Label ok;
 173     __ cmpw(Address(rsp, 0), StubRoutines::fpu_cntrl_wrd_std());
 174     __ jccb(Assembler::equal, ok);
 175     __ stop("corrupted control word detected");
 176     __ bind(ok);
 177 #endif
 178 
 179     // Reset the control word to guard against exceptions being unmasked
 180     // since fstp_d can cause FPU stack underflow exceptions.  Write it
 181     // into the on stack copy and then reload that to make sure that the
 182     // current and future values are correct.
 183     __ movw(Address(rsp, 0), StubRoutines::fpu_cntrl_wrd_std());
 184   }
 185 
 186   __ frstor(Address(rsp, 0));
 187   if (!verify_fpu) {
 188     // Set the control word so that exceptions are masked for the
 189     // following code.
 190     __ fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_std()));
 191   }
 192 
 193   int off = st0_off;
 194   int delta = st1_off - off;
 195 
 196   // Save the FPU registers in de-opt-able form
 197   for (int n = 0; n < FloatRegisterImpl::number_of_registers; n++) {
 198     __ fstp_d(Address(rsp, off*wordSize));
 199     off += delta;
 200   }
 201 
 202   off = xmm0_off;
 203   delta = xmm1_off - off;
 204   if(UseSSE == 1) {
 205     // Save the XMM state
 206     for (int n = 0; n < num_xmm_regs; n++) {
 207       __ movflt(Address(rsp, off*wordSize), as_XMMRegister(n));
 208       off += delta;
 209     }
 210   } else if(UseSSE >= 2) {
 211     // Save whole 128bit (16 bytes) XMM registers
 212     for (int n = 0; n < num_xmm_regs; n++) {
 213       __ movdqu(Address(rsp, off*wordSize), as_XMMRegister(n));
 214       off += delta;
 215     }
 216   }
 217 
 218   if (save_vectors) {
 219     __ subptr(rsp, ymm_bytes);
 220     // Save upper half of YMM registers
 221     for (int n = 0; n < num_xmm_regs; n++) {
 222       __ vextractf128_high(Address(rsp, n*16), as_XMMRegister(n));
 223     }
 224     if (UseAVX > 2) {
 225       __ subptr(rsp, zmm_bytes);
 226       // Save upper half of ZMM registers
 227       for (int n = 0; n < num_xmm_regs; n++) {
 228         __ vextractf64x4_high(Address(rsp, n*32), as_XMMRegister(n));
 229       }
 230     }
 231   }
 232   __ vzeroupper();
 233 
 234   // Set an oopmap for the call site.  This oopmap will map all
 235   // oop-registers and debug-info registers as callee-saved.  This
 236   // will allow deoptimization at this safepoint to find all possible
 237   // debug-info recordings, as well as let GC find all oops.
 238 
 239   OopMapSet *oop_maps = new OopMapSet();
 240   OopMap* map =  new OopMap( frame_words, 0 );
 241 
 242 #define STACK_OFFSET(x) VMRegImpl::stack2reg((x) + additional_frame_words)
 243 #define NEXTREG(x) (x)->as_VMReg()->next()
 244 
 245   map->set_callee_saved(STACK_OFFSET(rax_off), rax->as_VMReg());
 246   map->set_callee_saved(STACK_OFFSET(rcx_off), rcx->as_VMReg());
 247   map->set_callee_saved(STACK_OFFSET(rdx_off), rdx->as_VMReg());
 248   map->set_callee_saved(STACK_OFFSET(rbx_off), rbx->as_VMReg());
 249   // rbp, location is known implicitly, no oopMap
 250   map->set_callee_saved(STACK_OFFSET(rsi_off), rsi->as_VMReg());
 251   map->set_callee_saved(STACK_OFFSET(rdi_off), rdi->as_VMReg());
 252   // %%% This is really a waste but we'll keep things as they were for now for the upper component
 253   off = st0_off;
 254   delta = st1_off - off;
 255   for (int n = 0; n < FloatRegisterImpl::number_of_registers; n++) {
 256     FloatRegister freg_name = as_FloatRegister(n);
 257     map->set_callee_saved(STACK_OFFSET(off), freg_name->as_VMReg());
 258     map->set_callee_saved(STACK_OFFSET(off+1), NEXTREG(freg_name));
 259     off += delta;
 260   }
 261   off = xmm0_off;
 262   delta = xmm1_off - off;
 263   for (int n = 0; n < num_xmm_regs; n++) {
 264     XMMRegister xmm_name = as_XMMRegister(n);
 265     map->set_callee_saved(STACK_OFFSET(off), xmm_name->as_VMReg());
 266     map->set_callee_saved(STACK_OFFSET(off+1), NEXTREG(xmm_name));
 267     off += delta;
 268   }
 269 #undef NEXTREG
 270 #undef STACK_OFFSET
 271 
 272   return map;
 273 }
 274 
 275 void RegisterSaver::restore_live_registers(MacroAssembler* masm, bool restore_vectors) {
 276   int num_xmm_regs = XMMRegisterImpl::number_of_registers;
 277   int ymm_bytes = num_xmm_regs * 16;
 278   int zmm_bytes = num_xmm_regs * 32;
 279   // Recover XMM & FPU state
 280   int additional_frame_bytes = 0;
 281 #ifdef COMPILER2
 282   if (restore_vectors) {
 283     assert(UseAVX > 0, "Vectors larger than 16 byte long are supported only with AVX");
 284     assert(MaxVectorSize <= 64, "Only up to 64 byte long vectors are supported");
 285     // Save upper half of YMM registers
 286     additional_frame_bytes = ymm_bytes;
 287     if (UseAVX > 2) {
 288       // Save upper half of ZMM registers as well
 289       additional_frame_bytes += zmm_bytes;
 290     }
 291   }
 292 #else
 293   assert(!restore_vectors, "vectors are generated only by C2");
 294 #endif
 295 
 296   int off = xmm0_off;
 297   int delta = xmm1_off - off;
 298 
 299   __ vzeroupper();
 300 
 301   if (UseSSE == 1) {
 302     // Restore XMM registers
 303     assert(additional_frame_bytes == 0, "");
 304     for (int n = 0; n < num_xmm_regs; n++) {
 305       __ movflt(as_XMMRegister(n), Address(rsp, off*wordSize));
 306       off += delta;
 307     }
 308   } else if (UseSSE >= 2) {
 309     // Restore whole 128bit (16 bytes) XMM registers. Do this before restoring YMM and
 310     // ZMM because the movdqu instruction zeros the upper part of the XMM register.
 311     for (int n = 0; n < num_xmm_regs; n++) {
 312       __ movdqu(as_XMMRegister(n), Address(rsp, off*wordSize+additional_frame_bytes));
 313       off += delta;
 314     }
 315   }
 316 
 317   if (restore_vectors) {
 318     if (UseAVX > 2) {
 319       // Restore upper half of ZMM registers.
 320       for (int n = 0; n < num_xmm_regs; n++) {
 321         __ vinsertf64x4_high(as_XMMRegister(n), Address(rsp, n*32));
 322       }
 323       __ addptr(rsp, zmm_bytes);
 324     }
 325     // Restore upper half of YMM registers.
 326     for (int n = 0; n < num_xmm_regs; n++) {
 327       __ vinsertf128_high(as_XMMRegister(n), Address(rsp, n*16));
 328     }
 329     __ addptr(rsp, ymm_bytes);
 330   }
 331 
 332   __ pop_FPU_state();
 333   __ addptr(rsp, FPU_regs_live*wordSize); // Pop FPU registers
 334 
 335   __ popf();
 336   __ popa();
 337   // Get the rbp, described implicitly by the frame sender code (no oopMap)
 338   __ pop(rbp);
 339 }
 340 
 341 void RegisterSaver::restore_result_registers(MacroAssembler* masm) {
 342 
 343   // Just restore result register. Only used by deoptimization. By
 344   // now any callee save register that needs to be restore to a c2
 345   // caller of the deoptee has been extracted into the vframeArray
 346   // and will be stuffed into the c2i adapter we create for later
 347   // restoration so only result registers need to be restored here.
 348   //
 349 
 350   __ frstor(Address(rsp, 0));      // Restore fpu state
 351 
 352   // Recover XMM & FPU state
 353   if( UseSSE == 1 ) {
 354     __ movflt(xmm0, Address(rsp, xmm0_off*wordSize));
 355   } else if( UseSSE >= 2 ) {
 356     __ movdbl(xmm0, Address(rsp, xmm0_off*wordSize));
 357   }
 358   __ movptr(rax, Address(rsp, rax_off*wordSize));
 359   __ movptr(rdx, Address(rsp, rdx_off*wordSize));
 360   // Pop all of the register save are off the stack except the return address
 361   __ addptr(rsp, return_off * wordSize);
 362 }
 363 
 364 // Is vector's size (in bytes) bigger than a size saved by default?
 365 // 16 bytes XMM registers are saved by default using SSE2 movdqu instructions.
 366 // Note, MaxVectorSize == 0 with UseSSE < 2 and vectors are not generated.
 367 bool SharedRuntime::is_wide_vector(int size) {
 368   return size > 16;
 369 }
 370 
 371 size_t SharedRuntime::trampoline_size() {
 372   return 16;
 373 }
 374 
 375 void SharedRuntime::generate_trampoline(MacroAssembler *masm, address destination) {
 376   __ jump(RuntimeAddress(destination));
 377 }
 378 
 379 // The java_calling_convention describes stack locations as ideal slots on
 380 // a frame with no abi restrictions. Since we must observe abi restrictions
 381 // (like the placement of the register window) the slots must be biased by
 382 // the following value.
 383 static int reg2offset_in(VMReg r) {
 384   // Account for saved rbp, and return address
 385   // This should really be in_preserve_stack_slots
 386   return (r->reg2stack() + 2) * VMRegImpl::stack_slot_size;
 387 }
 388 
 389 static int reg2offset_out(VMReg r) {
 390   return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
 391 }
 392 
 393 // ---------------------------------------------------------------------------
 394 // Read the array of BasicTypes from a signature, and compute where the
 395 // arguments should go.  Values in the VMRegPair regs array refer to 4-byte
 396 // quantities.  Values less than SharedInfo::stack0 are registers, those above
 397 // refer to 4-byte stack slots.  All stack slots are based off of the stack pointer
 398 // as framesizes are fixed.
 399 // VMRegImpl::stack0 refers to the first slot 0(sp).
 400 // and VMRegImpl::stack0+1 refers to the memory word 4-byes higher.  Register
 401 // up to RegisterImpl::number_of_registers) are the 32-bit
 402 // integer registers.
 403 
 404 // Pass first two oop/int args in registers ECX and EDX.
 405 // Pass first two float/double args in registers XMM0 and XMM1.
 406 // Doubles have precedence, so if you pass a mix of floats and doubles
 407 // the doubles will grab the registers before the floats will.
 408 
 409 // Note: the INPUTS in sig_bt are in units of Java argument words, which are
 410 // either 32-bit or 64-bit depending on the build.  The OUTPUTS are in 32-bit
 411 // units regardless of build. Of course for i486 there is no 64 bit build
 412 
 413 
 414 // ---------------------------------------------------------------------------
 415 // The compiled Java calling convention.
 416 // Pass first two oop/int args in registers ECX and EDX.
 417 // Pass first two float/double args in registers XMM0 and XMM1.
 418 // Doubles have precedence, so if you pass a mix of floats and doubles
 419 // the doubles will grab the registers before the floats will.
 420 int SharedRuntime::java_calling_convention(const BasicType *sig_bt,
 421                                            VMRegPair *regs,
 422                                            int total_args_passed,
 423                                            int is_outgoing) {
 424   uint    stack = 0;          // Starting stack position for args on stack
 425 
 426 
 427   // Pass first two oop/int args in registers ECX and EDX.
 428   uint reg_arg0 = 9999;
 429   uint reg_arg1 = 9999;
 430 
 431   // Pass first two float/double args in registers XMM0 and XMM1.
 432   // Doubles have precedence, so if you pass a mix of floats and doubles
 433   // the doubles will grab the registers before the floats will.
 434   // CNC - TURNED OFF FOR non-SSE.
 435   //       On Intel we have to round all doubles (and most floats) at
 436   //       call sites by storing to the stack in any case.
 437   // UseSSE=0 ==> Don't Use ==> 9999+0
 438   // UseSSE=1 ==> Floats only ==> 9999+1
 439   // UseSSE>=2 ==> Floats or doubles ==> 9999+2
 440   enum { fltarg_dontuse = 9999+0, fltarg_float_only = 9999+1, fltarg_flt_dbl = 9999+2 };
 441   uint fargs = (UseSSE>=2) ? 2 : UseSSE;
 442   uint freg_arg0 = 9999+fargs;
 443   uint freg_arg1 = 9999+fargs;
 444 
 445   // Pass doubles & longs aligned on the stack.  First count stack slots for doubles
 446   int i;
 447   for( i = 0; i < total_args_passed; i++) {
 448     if( sig_bt[i] == T_DOUBLE ) {
 449       // first 2 doubles go in registers
 450       if( freg_arg0 == fltarg_flt_dbl ) freg_arg0 = i;
 451       else if( freg_arg1 == fltarg_flt_dbl ) freg_arg1 = i;
 452       else // Else double is passed low on the stack to be aligned.
 453         stack += 2;
 454     } else if( sig_bt[i] == T_LONG ) {
 455       stack += 2;
 456     }
 457   }
 458   int dstack = 0;             // Separate counter for placing doubles
 459 
 460   // Now pick where all else goes.
 461   for( i = 0; i < total_args_passed; i++) {
 462     // From the type and the argument number (count) compute the location
 463     switch( sig_bt[i] ) {
 464     case T_SHORT:
 465     case T_CHAR:
 466     case T_BYTE:
 467     case T_BOOLEAN:
 468     case T_INT:
 469     case T_ARRAY:
 470     case T_OBJECT:
 471     case T_ADDRESS:
 472       if( reg_arg0 == 9999 )  {
 473         reg_arg0 = i;
 474         regs[i].set1(rcx->as_VMReg());
 475       } else if( reg_arg1 == 9999 )  {
 476         reg_arg1 = i;
 477         regs[i].set1(rdx->as_VMReg());
 478       } else {
 479         regs[i].set1(VMRegImpl::stack2reg(stack++));
 480       }
 481       break;
 482     case T_FLOAT:
 483       if( freg_arg0 == fltarg_flt_dbl || freg_arg0 == fltarg_float_only ) {
 484         freg_arg0 = i;
 485         regs[i].set1(xmm0->as_VMReg());
 486       } else if( freg_arg1 == fltarg_flt_dbl || freg_arg1 == fltarg_float_only ) {
 487         freg_arg1 = i;
 488         regs[i].set1(xmm1->as_VMReg());
 489       } else {
 490         regs[i].set1(VMRegImpl::stack2reg(stack++));
 491       }
 492       break;
 493     case T_LONG:
 494       assert((i + 1) < total_args_passed && sig_bt[i+1] == T_VOID, "missing Half" );
 495       regs[i].set2(VMRegImpl::stack2reg(dstack));
 496       dstack += 2;
 497       break;
 498     case T_DOUBLE:
 499       assert((i + 1) < total_args_passed && sig_bt[i+1] == T_VOID, "missing Half" );
 500       if( freg_arg0 == (uint)i ) {
 501         regs[i].set2(xmm0->as_VMReg());
 502       } else if( freg_arg1 == (uint)i ) {
 503         regs[i].set2(xmm1->as_VMReg());
 504       } else {
 505         regs[i].set2(VMRegImpl::stack2reg(dstack));
 506         dstack += 2;
 507       }
 508       break;
 509     case T_VOID: regs[i].set_bad(); break;
 510       break;
 511     default:
 512       ShouldNotReachHere();
 513       break;
 514     }
 515   }
 516 
 517   // return value can be odd number of VMRegImpl stack slots make multiple of 2
 518   return align_up(stack, 2);
 519 }
 520 
 521 // Patch the callers callsite with entry to compiled code if it exists.
 522 static void patch_callers_callsite(MacroAssembler *masm) {
 523   Label L;
 524   __ cmpptr(Address(rbx, in_bytes(Method::code_offset())), (int32_t)NULL_WORD);
 525   __ jcc(Assembler::equal, L);
 526   // Schedule the branch target address early.
 527   // Call into the VM to patch the caller, then jump to compiled callee
 528   // rax, isn't live so capture return address while we easily can
 529   __ movptr(rax, Address(rsp, 0));
 530   __ pusha();
 531   __ pushf();
 532 
 533   if (UseSSE == 1) {
 534     __ subptr(rsp, 2*wordSize);
 535     __ movflt(Address(rsp, 0), xmm0);
 536     __ movflt(Address(rsp, wordSize), xmm1);
 537   }
 538   if (UseSSE >= 2) {
 539     __ subptr(rsp, 4*wordSize);
 540     __ movdbl(Address(rsp, 0), xmm0);
 541     __ movdbl(Address(rsp, 2*wordSize), xmm1);
 542   }
 543 #ifdef COMPILER2
 544   // C2 may leave the stack dirty if not in SSE2+ mode
 545   if (UseSSE >= 2) {
 546     __ verify_FPU(0, "c2i transition should have clean FPU stack");
 547   } else {
 548     __ empty_FPU_stack();
 549   }
 550 #endif /* COMPILER2 */
 551 
 552   // VM needs caller's callsite
 553   __ push(rax);
 554   // VM needs target method
 555   __ push(rbx);
 556   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::fixup_callers_callsite)));
 557   __ addptr(rsp, 2*wordSize);
 558 
 559   if (UseSSE == 1) {
 560     __ movflt(xmm0, Address(rsp, 0));
 561     __ movflt(xmm1, Address(rsp, wordSize));
 562     __ addptr(rsp, 2*wordSize);
 563   }
 564   if (UseSSE >= 2) {
 565     __ movdbl(xmm0, Address(rsp, 0));
 566     __ movdbl(xmm1, Address(rsp, 2*wordSize));
 567     __ addptr(rsp, 4*wordSize);
 568   }
 569 
 570   __ popf();
 571   __ popa();
 572   __ bind(L);
 573 }
 574 
 575 
 576 static void move_c2i_double(MacroAssembler *masm, XMMRegister r, int st_off) {
 577   int next_off = st_off - Interpreter::stackElementSize;
 578   __ movdbl(Address(rsp, next_off), r);
 579 }
 580 
 581 static void gen_c2i_adapter(MacroAssembler *masm,
 582                             int total_args_passed,
 583                             int comp_args_on_stack,
 584                             const BasicType *sig_bt,
 585                             const VMRegPair *regs,
 586                             Label& skip_fixup) {
 587   // Before we get into the guts of the C2I adapter, see if we should be here
 588   // at all.  We've come from compiled code and are attempting to jump to the
 589   // interpreter, which means the caller made a static call to get here
 590   // (vcalls always get a compiled target if there is one).  Check for a
 591   // compiled target.  If there is one, we need to patch the caller's call.
 592   patch_callers_callsite(masm);
 593 
 594   __ bind(skip_fixup);
 595 
 596 #ifdef COMPILER2
 597   // C2 may leave the stack dirty if not in SSE2+ mode
 598   if (UseSSE >= 2) {
 599     __ verify_FPU(0, "c2i transition should have clean FPU stack");
 600   } else {
 601     __ empty_FPU_stack();
 602   }
 603 #endif /* COMPILER2 */
 604 
 605   // Since all args are passed on the stack, total_args_passed * interpreter_
 606   // stack_element_size  is the
 607   // space we need.
 608   int extraspace = total_args_passed * Interpreter::stackElementSize;
 609 
 610   // Get return address
 611   __ pop(rax);
 612 
 613   // set senderSP value
 614   __ movptr(rsi, rsp);
 615 
 616   __ subptr(rsp, extraspace);
 617 
 618   // Now write the args into the outgoing interpreter space
 619   for (int i = 0; i < total_args_passed; i++) {
 620     if (sig_bt[i] == T_VOID) {
 621       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
 622       continue;
 623     }
 624 
 625     // st_off points to lowest address on stack.
 626     int st_off = ((total_args_passed - 1) - i) * Interpreter::stackElementSize;
 627     int next_off = st_off - Interpreter::stackElementSize;
 628 
 629     // Say 4 args:
 630     // i   st_off
 631     // 0   12 T_LONG
 632     // 1    8 T_VOID
 633     // 2    4 T_OBJECT
 634     // 3    0 T_BOOL
 635     VMReg r_1 = regs[i].first();
 636     VMReg r_2 = regs[i].second();
 637     if (!r_1->is_valid()) {
 638       assert(!r_2->is_valid(), "");
 639       continue;
 640     }
 641 
 642     if (r_1->is_stack()) {
 643       // memory to memory use fpu stack top
 644       int ld_off = r_1->reg2stack() * VMRegImpl::stack_slot_size + extraspace;
 645 
 646       if (!r_2->is_valid()) {
 647         __ movl(rdi, Address(rsp, ld_off));
 648         __ movptr(Address(rsp, st_off), rdi);
 649       } else {
 650 
 651         // ld_off == LSW, ld_off+VMRegImpl::stack_slot_size == MSW
 652         // st_off == MSW, st_off-wordSize == LSW
 653 
 654         __ movptr(rdi, Address(rsp, ld_off));
 655         __ movptr(Address(rsp, next_off), rdi);
 656 #ifndef _LP64
 657         __ movptr(rdi, Address(rsp, ld_off + wordSize));
 658         __ movptr(Address(rsp, st_off), rdi);
 659 #else
 660 #ifdef ASSERT
 661         // Overwrite the unused slot with known junk
 662         __ mov64(rax, CONST64(0xdeadffffdeadaaaa));
 663         __ movptr(Address(rsp, st_off), rax);
 664 #endif /* ASSERT */
 665 #endif // _LP64
 666       }
 667     } else if (r_1->is_Register()) {
 668       Register r = r_1->as_Register();
 669       if (!r_2->is_valid()) {
 670         __ movl(Address(rsp, st_off), r);
 671       } else {
 672         // long/double in gpr
 673         NOT_LP64(ShouldNotReachHere());
 674         // Two VMRegs can be T_OBJECT, T_ADDRESS, T_DOUBLE, T_LONG
 675         // T_DOUBLE and T_LONG use two slots in the interpreter
 676         if ( sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
 677           // long/double in gpr
 678 #ifdef ASSERT
 679           // Overwrite the unused slot with known junk
 680           LP64_ONLY(__ mov64(rax, CONST64(0xdeadffffdeadaaab)));
 681           __ movptr(Address(rsp, st_off), rax);
 682 #endif /* ASSERT */
 683           __ movptr(Address(rsp, next_off), r);
 684         } else {
 685           __ movptr(Address(rsp, st_off), r);
 686         }
 687       }
 688     } else {
 689       assert(r_1->is_XMMRegister(), "");
 690       if (!r_2->is_valid()) {
 691         __ movflt(Address(rsp, st_off), r_1->as_XMMRegister());
 692       } else {
 693         assert(sig_bt[i] == T_DOUBLE || sig_bt[i] == T_LONG, "wrong type");
 694         move_c2i_double(masm, r_1->as_XMMRegister(), st_off);
 695       }
 696     }
 697   }
 698 
 699   // Schedule the branch target address early.
 700   __ movptr(rcx, Address(rbx, in_bytes(Method::interpreter_entry_offset())));
 701   // And repush original return address
 702   __ push(rax);
 703   __ jmp(rcx);
 704 }
 705 
 706 
 707 static void move_i2c_double(MacroAssembler *masm, XMMRegister r, Register saved_sp, int ld_off) {
 708   int next_val_off = ld_off - Interpreter::stackElementSize;
 709   __ movdbl(r, Address(saved_sp, next_val_off));
 710 }
 711 
 712 static void range_check(MacroAssembler* masm, Register pc_reg, Register temp_reg,
 713                         address code_start, address code_end,
 714                         Label& L_ok) {
 715   Label L_fail;
 716   __ lea(temp_reg, ExternalAddress(code_start));
 717   __ cmpptr(pc_reg, temp_reg);
 718   __ jcc(Assembler::belowEqual, L_fail);
 719   __ lea(temp_reg, ExternalAddress(code_end));
 720   __ cmpptr(pc_reg, temp_reg);
 721   __ jcc(Assembler::below, L_ok);
 722   __ bind(L_fail);
 723 }
 724 
 725 void SharedRuntime::gen_i2c_adapter(MacroAssembler *masm,
 726                                     int total_args_passed,
 727                                     int comp_args_on_stack,
 728                                     const BasicType *sig_bt,
 729                                     const VMRegPair *regs) {
 730   // Note: rsi contains the senderSP on entry. We must preserve it since
 731   // we may do a i2c -> c2i transition if we lose a race where compiled
 732   // code goes non-entrant while we get args ready.
 733 
 734   // Adapters can be frameless because they do not require the caller
 735   // to perform additional cleanup work, such as correcting the stack pointer.
 736   // An i2c adapter is frameless because the *caller* frame, which is interpreted,
 737   // routinely repairs its own stack pointer (from interpreter_frame_last_sp),
 738   // even if a callee has modified the stack pointer.
 739   // A c2i adapter is frameless because the *callee* frame, which is interpreted,
 740   // routinely repairs its caller's stack pointer (from sender_sp, which is set
 741   // up via the senderSP register).
 742   // In other words, if *either* the caller or callee is interpreted, we can
 743   // get the stack pointer repaired after a call.
 744   // This is why c2i and i2c adapters cannot be indefinitely composed.
 745   // In particular, if a c2i adapter were to somehow call an i2c adapter,
 746   // both caller and callee would be compiled methods, and neither would
 747   // clean up the stack pointer changes performed by the two adapters.
 748   // If this happens, control eventually transfers back to the compiled
 749   // caller, but with an uncorrected stack, causing delayed havoc.
 750 
 751   // Pick up the return address
 752   __ movptr(rax, Address(rsp, 0));
 753 
 754   if (VerifyAdapterCalls &&
 755       (Interpreter::code() != NULL || StubRoutines::code1() != NULL)) {
 756     // So, let's test for cascading c2i/i2c adapters right now.
 757     //  assert(Interpreter::contains($return_addr) ||
 758     //         StubRoutines::contains($return_addr),
 759     //         "i2c adapter must return to an interpreter frame");
 760     __ block_comment("verify_i2c { ");
 761     Label L_ok;
 762     if (Interpreter::code() != NULL)
 763       range_check(masm, rax, rdi,
 764                   Interpreter::code()->code_start(), Interpreter::code()->code_end(),
 765                   L_ok);
 766     if (StubRoutines::code1() != NULL)
 767       range_check(masm, rax, rdi,
 768                   StubRoutines::code1()->code_begin(), StubRoutines::code1()->code_end(),
 769                   L_ok);
 770     if (StubRoutines::code2() != NULL)
 771       range_check(masm, rax, rdi,
 772                   StubRoutines::code2()->code_begin(), StubRoutines::code2()->code_end(),
 773                   L_ok);
 774     const char* msg = "i2c adapter must return to an interpreter frame";
 775     __ block_comment(msg);
 776     __ stop(msg);
 777     __ bind(L_ok);
 778     __ block_comment("} verify_i2ce ");
 779   }
 780 
 781   // Must preserve original SP for loading incoming arguments because
 782   // we need to align the outgoing SP for compiled code.
 783   __ movptr(rdi, rsp);
 784 
 785   // Cut-out for having no stack args.  Since up to 2 int/oop args are passed
 786   // in registers, we will occasionally have no stack args.
 787   int comp_words_on_stack = 0;
 788   if (comp_args_on_stack) {
 789     // Sig words on the stack are greater-than VMRegImpl::stack0.  Those in
 790     // registers are below.  By subtracting stack0, we either get a negative
 791     // number (all values in registers) or the maximum stack slot accessed.
 792     // int comp_args_on_stack = VMRegImpl::reg2stack(max_arg);
 793     // Convert 4-byte stack slots to words.
 794     comp_words_on_stack = align_up(comp_args_on_stack*4, wordSize)>>LogBytesPerWord;
 795     // Round up to miminum stack alignment, in wordSize
 796     comp_words_on_stack = align_up(comp_words_on_stack, 2);
 797     __ subptr(rsp, comp_words_on_stack * wordSize);
 798   }
 799 
 800   // Align the outgoing SP
 801   __ andptr(rsp, -(StackAlignmentInBytes));
 802 
 803   // push the return address on the stack (note that pushing, rather
 804   // than storing it, yields the correct frame alignment for the callee)
 805   __ push(rax);
 806 
 807   // Put saved SP in another register
 808   const Register saved_sp = rax;
 809   __ movptr(saved_sp, rdi);
 810 
 811 
 812   // Will jump to the compiled code just as if compiled code was doing it.
 813   // Pre-load the register-jump target early, to schedule it better.
 814   __ movptr(rdi, Address(rbx, in_bytes(Method::from_compiled_offset())));
 815 
 816   // Now generate the shuffle code.  Pick up all register args and move the
 817   // rest through the floating point stack top.
 818   for (int i = 0; i < total_args_passed; i++) {
 819     if (sig_bt[i] == T_VOID) {
 820       // Longs and doubles are passed in native word order, but misaligned
 821       // in the 32-bit build.
 822       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
 823       continue;
 824     }
 825 
 826     // Pick up 0, 1 or 2 words from SP+offset.
 827 
 828     assert(!regs[i].second()->is_valid() || regs[i].first()->next() == regs[i].second(),
 829             "scrambled load targets?");
 830     // Load in argument order going down.
 831     int ld_off = (total_args_passed - i) * Interpreter::stackElementSize;
 832     // Point to interpreter value (vs. tag)
 833     int next_off = ld_off - Interpreter::stackElementSize;
 834     //
 835     //
 836     //
 837     VMReg r_1 = regs[i].first();
 838     VMReg r_2 = regs[i].second();
 839     if (!r_1->is_valid()) {
 840       assert(!r_2->is_valid(), "");
 841       continue;
 842     }
 843     if (r_1->is_stack()) {
 844       // Convert stack slot to an SP offset (+ wordSize to account for return address )
 845       int st_off = regs[i].first()->reg2stack()*VMRegImpl::stack_slot_size + wordSize;
 846 
 847       // We can use rsi as a temp here because compiled code doesn't need rsi as an input
 848       // and if we end up going thru a c2i because of a miss a reasonable value of rsi
 849       // we be generated.
 850       if (!r_2->is_valid()) {
 851         // __ fld_s(Address(saved_sp, ld_off));
 852         // __ fstp_s(Address(rsp, st_off));
 853         __ movl(rsi, Address(saved_sp, ld_off));
 854         __ movptr(Address(rsp, st_off), rsi);
 855       } else {
 856         // Interpreter local[n] == MSW, local[n+1] == LSW however locals
 857         // are accessed as negative so LSW is at LOW address
 858 
 859         // ld_off is MSW so get LSW
 860         // st_off is LSW (i.e. reg.first())
 861         // __ fld_d(Address(saved_sp, next_off));
 862         // __ fstp_d(Address(rsp, st_off));
 863         //
 864         // We are using two VMRegs. This can be either T_OBJECT, T_ADDRESS, T_LONG, or T_DOUBLE
 865         // the interpreter allocates two slots but only uses one for thr T_LONG or T_DOUBLE case
 866         // So we must adjust where to pick up the data to match the interpreter.
 867         //
 868         // Interpreter local[n] == MSW, local[n+1] == LSW however locals
 869         // are accessed as negative so LSW is at LOW address
 870 
 871         // ld_off is MSW so get LSW
 872         const int offset = (NOT_LP64(true ||) sig_bt[i]==T_LONG||sig_bt[i]==T_DOUBLE)?
 873                            next_off : ld_off;
 874         __ movptr(rsi, Address(saved_sp, offset));
 875         __ movptr(Address(rsp, st_off), rsi);
 876 #ifndef _LP64
 877         __ movptr(rsi, Address(saved_sp, ld_off));
 878         __ movptr(Address(rsp, st_off + wordSize), rsi);
 879 #endif // _LP64
 880       }
 881     } else if (r_1->is_Register()) {  // Register argument
 882       Register r = r_1->as_Register();
 883       assert(r != rax, "must be different");
 884       if (r_2->is_valid()) {
 885         //
 886         // We are using two VMRegs. This can be either T_OBJECT, T_ADDRESS, T_LONG, or T_DOUBLE
 887         // the interpreter allocates two slots but only uses one for thr T_LONG or T_DOUBLE case
 888         // So we must adjust where to pick up the data to match the interpreter.
 889 
 890         const int offset = (NOT_LP64(true ||) sig_bt[i]==T_LONG||sig_bt[i]==T_DOUBLE)?
 891                            next_off : ld_off;
 892 
 893         // this can be a misaligned move
 894         __ movptr(r, Address(saved_sp, offset));
 895 #ifndef _LP64
 896         assert(r_2->as_Register() != rax, "need another temporary register");
 897         // Remember r_1 is low address (and LSB on x86)
 898         // So r_2 gets loaded from high address regardless of the platform
 899         __ movptr(r_2->as_Register(), Address(saved_sp, ld_off));
 900 #endif // _LP64
 901       } else {
 902         __ movl(r, Address(saved_sp, ld_off));
 903       }
 904     } else {
 905       assert(r_1->is_XMMRegister(), "");
 906       if (!r_2->is_valid()) {
 907         __ movflt(r_1->as_XMMRegister(), Address(saved_sp, ld_off));
 908       } else {
 909         move_i2c_double(masm, r_1->as_XMMRegister(), saved_sp, ld_off);
 910       }
 911     }
 912   }
 913 
 914   // 6243940 We might end up in handle_wrong_method if
 915   // the callee is deoptimized as we race thru here. If that
 916   // happens we don't want to take a safepoint because the
 917   // caller frame will look interpreted and arguments are now
 918   // "compiled" so it is much better to make this transition
 919   // invisible to the stack walking code. Unfortunately if
 920   // we try and find the callee by normal means a safepoint
 921   // is possible. So we stash the desired callee in the thread
 922   // and the vm will find there should this case occur.
 923 
 924   __ get_thread(rax);
 925   __ movptr(Address(rax, JavaThread::callee_target_offset()), rbx);
 926 
 927   // move Method* to rax, in case we end up in an c2i adapter.
 928   // the c2i adapters expect Method* in rax, (c2) because c2's
 929   // resolve stubs return the result (the method) in rax,.
 930   // I'd love to fix this.
 931   __ mov(rax, rbx);
 932 
 933   __ jmp(rdi);
 934 }
 935 
 936 // ---------------------------------------------------------------
 937 AdapterHandlerEntry* SharedRuntime::generate_i2c2i_adapters(MacroAssembler *masm,
 938                                                             int total_args_passed,
 939                                                             int comp_args_on_stack,
 940                                                             const BasicType *sig_bt,
 941                                                             const VMRegPair *regs,
 942                                                             AdapterFingerPrint* fingerprint) {
 943   address i2c_entry = __ pc();
 944 
 945   gen_i2c_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs);
 946 
 947   // -------------------------------------------------------------------------
 948   // Generate a C2I adapter.  On entry we know rbx, holds the Method* during calls
 949   // to the interpreter.  The args start out packed in the compiled layout.  They
 950   // need to be unpacked into the interpreter layout.  This will almost always
 951   // require some stack space.  We grow the current (compiled) stack, then repack
 952   // the args.  We  finally end in a jump to the generic interpreter entry point.
 953   // On exit from the interpreter, the interpreter will restore our SP (lest the
 954   // compiled code, which relys solely on SP and not EBP, get sick).
 955 
 956   address c2i_unverified_entry = __ pc();
 957   Label skip_fixup;
 958 
 959   Register holder = rax;
 960   Register receiver = rcx;
 961   Register temp = rbx;
 962 
 963   {
 964 
 965     Label missed;
 966     __ movptr(temp, Address(receiver, oopDesc::klass_offset_in_bytes()));
 967     __ cmpptr(temp, Address(holder, CompiledICHolder::holder_klass_offset()));
 968     __ movptr(rbx, Address(holder, CompiledICHolder::holder_metadata_offset()));
 969     __ jcc(Assembler::notEqual, missed);
 970     // Method might have been compiled since the call site was patched to
 971     // interpreted if that is the case treat it as a miss so we can get
 972     // the call site corrected.
 973     __ cmpptr(Address(rbx, in_bytes(Method::code_offset())), (int32_t)NULL_WORD);
 974     __ jcc(Assembler::equal, skip_fixup);
 975 
 976     __ bind(missed);
 977     __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 978   }
 979 
 980   address c2i_entry = __ pc();
 981 
 982   gen_c2i_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs, skip_fixup);
 983 
 984   __ flush();
 985   return AdapterHandlerLibrary::new_entry(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry);
 986 }
 987 
 988 int SharedRuntime::c_calling_convention(const BasicType *sig_bt,
 989                                          VMRegPair *regs,
 990                                          VMRegPair *regs2,
 991                                          int total_args_passed) {
 992   assert(regs2 == NULL, "not needed on x86");
 993 // We return the amount of VMRegImpl stack slots we need to reserve for all
 994 // the arguments NOT counting out_preserve_stack_slots.
 995 
 996   uint    stack = 0;        // All arguments on stack
 997 
 998   for( int i = 0; i < total_args_passed; i++) {
 999     // From the type and the argument number (count) compute the location
1000     switch( sig_bt[i] ) {
1001     case T_BOOLEAN:
1002     case T_CHAR:
1003     case T_FLOAT:
1004     case T_BYTE:
1005     case T_SHORT:
1006     case T_INT:
1007     case T_OBJECT:
1008     case T_ARRAY:
1009     case T_ADDRESS:
1010     case T_METADATA:
1011       regs[i].set1(VMRegImpl::stack2reg(stack++));
1012       break;
1013     case T_LONG:
1014     case T_DOUBLE: // The stack numbering is reversed from Java
1015       // Since C arguments do not get reversed, the ordering for
1016       // doubles on the stack must be opposite the Java convention
1017       assert((i + 1) < total_args_passed && sig_bt[i+1] == T_VOID, "missing Half" );
1018       regs[i].set2(VMRegImpl::stack2reg(stack));
1019       stack += 2;
1020       break;
1021     case T_VOID: regs[i].set_bad(); break;
1022     default:
1023       ShouldNotReachHere();
1024       break;
1025     }
1026   }
1027   return stack;
1028 }
1029 
1030 // A simple move of integer like type
1031 static void simple_move32(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1032   if (src.first()->is_stack()) {
1033     if (dst.first()->is_stack()) {
1034       // stack to stack
1035       // __ ld(FP, reg2offset(src.first()) + STACK_BIAS, L5);
1036       // __ st(L5, SP, reg2offset(dst.first()) + STACK_BIAS);
1037       __ movl2ptr(rax, Address(rbp, reg2offset_in(src.first())));
1038       __ movptr(Address(rsp, reg2offset_out(dst.first())), rax);
1039     } else {
1040       // stack to reg
1041       __ movl2ptr(dst.first()->as_Register(),  Address(rbp, reg2offset_in(src.first())));
1042     }
1043   } else if (dst.first()->is_stack()) {
1044     // reg to stack
1045     // no need to sign extend on 64bit
1046     __ movptr(Address(rsp, reg2offset_out(dst.first())), src.first()->as_Register());
1047   } else {
1048     if (dst.first() != src.first()) {
1049       __ mov(dst.first()->as_Register(), src.first()->as_Register());
1050     }
1051   }
1052 }
1053 
1054 // An oop arg. Must pass a handle not the oop itself
1055 static void object_move(MacroAssembler* masm,
1056                         OopMap* map,
1057                         int oop_handle_offset,
1058                         int framesize_in_slots,
1059                         VMRegPair src,
1060                         VMRegPair dst,
1061                         bool is_receiver,
1062                         int* receiver_offset) {
1063 
1064   // Because of the calling conventions we know that src can be a
1065   // register or a stack location. dst can only be a stack location.
1066 
1067   assert(dst.first()->is_stack(), "must be stack");
1068   // must pass a handle. First figure out the location we use as a handle
1069 
1070   if (src.first()->is_stack()) {
1071     // Oop is already on the stack as an argument
1072     Register rHandle = rax;
1073     Label nil;
1074     __ xorptr(rHandle, rHandle);
1075     __ cmpptr(Address(rbp, reg2offset_in(src.first())), (int32_t)NULL_WORD);
1076     __ jcc(Assembler::equal, nil);
1077     __ lea(rHandle, Address(rbp, reg2offset_in(src.first())));
1078     __ bind(nil);
1079     __ movptr(Address(rsp, reg2offset_out(dst.first())), rHandle);
1080 
1081     int offset_in_older_frame = src.first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
1082     map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + framesize_in_slots));
1083     if (is_receiver) {
1084       *receiver_offset = (offset_in_older_frame + framesize_in_slots) * VMRegImpl::stack_slot_size;
1085     }
1086   } else {
1087     // Oop is in an a register we must store it to the space we reserve
1088     // on the stack for oop_handles
1089     const Register rOop = src.first()->as_Register();
1090     const Register rHandle = rax;
1091     int oop_slot = (rOop == rcx ? 0 : 1) * VMRegImpl::slots_per_word + oop_handle_offset;
1092     int offset = oop_slot*VMRegImpl::stack_slot_size;
1093     Label skip;
1094     __ movptr(Address(rsp, offset), rOop);
1095     map->set_oop(VMRegImpl::stack2reg(oop_slot));
1096     __ xorptr(rHandle, rHandle);
1097     __ cmpptr(rOop, (int32_t)NULL_WORD);
1098     __ jcc(Assembler::equal, skip);
1099     __ lea(rHandle, Address(rsp, offset));
1100     __ bind(skip);
1101     // Store the handle parameter
1102     __ movptr(Address(rsp, reg2offset_out(dst.first())), rHandle);
1103     if (is_receiver) {
1104       *receiver_offset = offset;
1105     }
1106   }
1107 }
1108 
1109 // A float arg may have to do float reg int reg conversion
1110 static void float_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1111   assert(!src.second()->is_valid() && !dst.second()->is_valid(), "bad float_move");
1112 
1113   // Because of the calling convention we know that src is either a stack location
1114   // or an xmm register. dst can only be a stack location.
1115 
1116   assert(dst.first()->is_stack() && ( src.first()->is_stack() || src.first()->is_XMMRegister()), "bad parameters");
1117 
1118   if (src.first()->is_stack()) {
1119     __ movl(rax, Address(rbp, reg2offset_in(src.first())));
1120     __ movptr(Address(rsp, reg2offset_out(dst.first())), rax);
1121   } else {
1122     // reg to stack
1123     __ movflt(Address(rsp, reg2offset_out(dst.first())), src.first()->as_XMMRegister());
1124   }
1125 }
1126 
1127 // A long move
1128 static void long_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1129 
1130   // The only legal possibility for a long_move VMRegPair is:
1131   // 1: two stack slots (possibly unaligned)
1132   // as neither the java  or C calling convention will use registers
1133   // for longs.
1134 
1135   if (src.first()->is_stack() && dst.first()->is_stack()) {
1136     assert(src.second()->is_stack() && dst.second()->is_stack(), "must be all stack");
1137     __ movptr(rax, Address(rbp, reg2offset_in(src.first())));
1138     NOT_LP64(__ movptr(rbx, Address(rbp, reg2offset_in(src.second()))));
1139     __ movptr(Address(rsp, reg2offset_out(dst.first())), rax);
1140     NOT_LP64(__ movptr(Address(rsp, reg2offset_out(dst.second())), rbx));
1141   } else {
1142     ShouldNotReachHere();
1143   }
1144 }
1145 
1146 // A double move
1147 static void double_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1148 
1149   // The only legal possibilities for a double_move VMRegPair are:
1150   // The painful thing here is that like long_move a VMRegPair might be
1151 
1152   // Because of the calling convention we know that src is either
1153   //   1: a single physical register (xmm registers only)
1154   //   2: two stack slots (possibly unaligned)
1155   // dst can only be a pair of stack slots.
1156 
1157   assert(dst.first()->is_stack() && (src.first()->is_XMMRegister() || src.first()->is_stack()), "bad args");
1158 
1159   if (src.first()->is_stack()) {
1160     // source is all stack
1161     __ movptr(rax, Address(rbp, reg2offset_in(src.first())));
1162     NOT_LP64(__ movptr(rbx, Address(rbp, reg2offset_in(src.second()))));
1163     __ movptr(Address(rsp, reg2offset_out(dst.first())), rax);
1164     NOT_LP64(__ movptr(Address(rsp, reg2offset_out(dst.second())), rbx));
1165   } else {
1166     // reg to stack
1167     // No worries about stack alignment
1168     __ movdbl(Address(rsp, reg2offset_out(dst.first())), src.first()->as_XMMRegister());
1169   }
1170 }
1171 
1172 
1173 void SharedRuntime::save_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1174   // We always ignore the frame_slots arg and just use the space just below frame pointer
1175   // which by this time is free to use
1176   switch (ret_type) {
1177   case T_FLOAT:
1178     __ fstp_s(Address(rbp, -wordSize));
1179     break;
1180   case T_DOUBLE:
1181     __ fstp_d(Address(rbp, -2*wordSize));
1182     break;
1183   case T_VOID:  break;
1184   case T_LONG:
1185     __ movptr(Address(rbp, -wordSize), rax);
1186     NOT_LP64(__ movptr(Address(rbp, -2*wordSize), rdx));
1187     break;
1188   default: {
1189     __ movptr(Address(rbp, -wordSize), rax);
1190     }
1191   }
1192 }
1193 
1194 void SharedRuntime::restore_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1195   // We always ignore the frame_slots arg and just use the space just below frame pointer
1196   // which by this time is free to use
1197   switch (ret_type) {
1198   case T_FLOAT:
1199     __ fld_s(Address(rbp, -wordSize));
1200     break;
1201   case T_DOUBLE:
1202     __ fld_d(Address(rbp, -2*wordSize));
1203     break;
1204   case T_LONG:
1205     __ movptr(rax, Address(rbp, -wordSize));
1206     NOT_LP64(__ movptr(rdx, Address(rbp, -2*wordSize)));
1207     break;
1208   case T_VOID:  break;
1209   default: {
1210     __ movptr(rax, Address(rbp, -wordSize));
1211     }
1212   }
1213 }
1214 
1215 
1216 static void save_or_restore_arguments(MacroAssembler* masm,
1217                                       const int stack_slots,
1218                                       const int total_in_args,
1219                                       const int arg_save_area,
1220                                       OopMap* map,
1221                                       VMRegPair* in_regs,
1222                                       BasicType* in_sig_bt) {
1223   // if map is non-NULL then the code should store the values,
1224   // otherwise it should load them.
1225   int handle_index = 0;
1226   // Save down double word first
1227   for ( int i = 0; i < total_in_args; i++) {
1228     if (in_regs[i].first()->is_XMMRegister() && in_sig_bt[i] == T_DOUBLE) {
1229       int slot = handle_index * VMRegImpl::slots_per_word + arg_save_area;
1230       int offset = slot * VMRegImpl::stack_slot_size;
1231       handle_index += 2;
1232       assert(handle_index <= stack_slots, "overflow");
1233       if (map != NULL) {
1234         __ movdbl(Address(rsp, offset), in_regs[i].first()->as_XMMRegister());
1235       } else {
1236         __ movdbl(in_regs[i].first()->as_XMMRegister(), Address(rsp, offset));
1237       }
1238     }
1239     if (in_regs[i].first()->is_Register() && in_sig_bt[i] == T_LONG) {
1240       int slot = handle_index * VMRegImpl::slots_per_word + arg_save_area;
1241       int offset = slot * VMRegImpl::stack_slot_size;
1242       handle_index += 2;
1243       assert(handle_index <= stack_slots, "overflow");
1244       if (map != NULL) {
1245         __ movl(Address(rsp, offset), in_regs[i].first()->as_Register());
1246         if (in_regs[i].second()->is_Register()) {
1247           __ movl(Address(rsp, offset + 4), in_regs[i].second()->as_Register());
1248         }
1249       } else {
1250         __ movl(in_regs[i].first()->as_Register(), Address(rsp, offset));
1251         if (in_regs[i].second()->is_Register()) {
1252           __ movl(in_regs[i].second()->as_Register(), Address(rsp, offset + 4));
1253         }
1254       }
1255     }
1256   }
1257   // Save or restore single word registers
1258   for ( int i = 0; i < total_in_args; i++) {
1259     if (in_regs[i].first()->is_Register()) {
1260       int slot = handle_index++ * VMRegImpl::slots_per_word + arg_save_area;
1261       int offset = slot * VMRegImpl::stack_slot_size;
1262       assert(handle_index <= stack_slots, "overflow");
1263       if (in_sig_bt[i] == T_ARRAY && map != NULL) {
1264         map->set_oop(VMRegImpl::stack2reg(slot));;
1265       }
1266 
1267       // Value is in an input register pass we must flush it to the stack
1268       const Register reg = in_regs[i].first()->as_Register();
1269       switch (in_sig_bt[i]) {
1270         case T_ARRAY:
1271           if (map != NULL) {
1272             __ movptr(Address(rsp, offset), reg);
1273           } else {
1274             __ movptr(reg, Address(rsp, offset));
1275           }
1276           break;
1277         case T_BOOLEAN:
1278         case T_CHAR:
1279         case T_BYTE:
1280         case T_SHORT:
1281         case T_INT:
1282           if (map != NULL) {
1283             __ movl(Address(rsp, offset), reg);
1284           } else {
1285             __ movl(reg, Address(rsp, offset));
1286           }
1287           break;
1288         case T_OBJECT:
1289         default: ShouldNotReachHere();
1290       }
1291     } else if (in_regs[i].first()->is_XMMRegister()) {
1292       if (in_sig_bt[i] == T_FLOAT) {
1293         int slot = handle_index++ * VMRegImpl::slots_per_word + arg_save_area;
1294         int offset = slot * VMRegImpl::stack_slot_size;
1295         assert(handle_index <= stack_slots, "overflow");
1296         if (map != NULL) {
1297           __ movflt(Address(rsp, offset), in_regs[i].first()->as_XMMRegister());
1298         } else {
1299           __ movflt(in_regs[i].first()->as_XMMRegister(), Address(rsp, offset));
1300         }
1301       }
1302     } else if (in_regs[i].first()->is_stack()) {
1303       if (in_sig_bt[i] == T_ARRAY && map != NULL) {
1304         int offset_in_older_frame = in_regs[i].first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
1305         map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + stack_slots));
1306       }
1307     }
1308   }
1309 }
1310 
1311 // Check GCLocker::needs_gc and enter the runtime if it's true.  This
1312 // keeps a new JNI critical region from starting until a GC has been
1313 // forced.  Save down any oops in registers and describe them in an
1314 // OopMap.
1315 static void check_needs_gc_for_critical_native(MacroAssembler* masm,
1316                                                Register thread,
1317                                                int stack_slots,
1318                                                int total_c_args,
1319                                                int total_in_args,
1320                                                int arg_save_area,
1321                                                OopMapSet* oop_maps,
1322                                                VMRegPair* in_regs,
1323                                                BasicType* in_sig_bt) {
1324   __ block_comment("check GCLocker::needs_gc");
1325   Label cont;
1326   __ cmp8(ExternalAddress((address)GCLocker::needs_gc_address()), false);
1327   __ jcc(Assembler::equal, cont);
1328 
1329   // Save down any incoming oops and call into the runtime to halt for a GC
1330 
1331   OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1332 
1333   save_or_restore_arguments(masm, stack_slots, total_in_args,
1334                             arg_save_area, map, in_regs, in_sig_bt);
1335 
1336   address the_pc = __ pc();
1337   oop_maps->add_gc_map( __ offset(), map);
1338   __ set_last_Java_frame(thread, rsp, noreg, the_pc);
1339 
1340   __ block_comment("block_for_jni_critical");
1341   __ push(thread);
1342   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::block_for_jni_critical)));
1343   __ increment(rsp, wordSize);
1344 
1345   __ get_thread(thread);
1346   __ reset_last_Java_frame(thread, false);
1347 
1348   save_or_restore_arguments(masm, stack_slots, total_in_args,
1349                             arg_save_area, NULL, in_regs, in_sig_bt);
1350 
1351   __ bind(cont);
1352 #ifdef ASSERT
1353   if (StressCriticalJNINatives) {
1354     // Stress register saving
1355     OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1356     save_or_restore_arguments(masm, stack_slots, total_in_args,
1357                               arg_save_area, map, in_regs, in_sig_bt);
1358     // Destroy argument registers
1359     for (int i = 0; i < total_in_args - 1; i++) {
1360       if (in_regs[i].first()->is_Register()) {
1361         const Register reg = in_regs[i].first()->as_Register();
1362         __ xorptr(reg, reg);
1363       } else if (in_regs[i].first()->is_XMMRegister()) {
1364         __ xorpd(in_regs[i].first()->as_XMMRegister(), in_regs[i].first()->as_XMMRegister());
1365       } else if (in_regs[i].first()->is_FloatRegister()) {
1366         ShouldNotReachHere();
1367       } else if (in_regs[i].first()->is_stack()) {
1368         // Nothing to do
1369       } else {
1370         ShouldNotReachHere();
1371       }
1372       if (in_sig_bt[i] == T_LONG || in_sig_bt[i] == T_DOUBLE) {
1373         i++;
1374       }
1375     }
1376 
1377     save_or_restore_arguments(masm, stack_slots, total_in_args,
1378                               arg_save_area, NULL, in_regs, in_sig_bt);
1379   }
1380 #endif
1381 }
1382 
1383 // Unpack an array argument into a pointer to the body and the length
1384 // if the array is non-null, otherwise pass 0 for both.
1385 static void unpack_array_argument(MacroAssembler* masm, VMRegPair reg, BasicType in_elem_type, VMRegPair body_arg, VMRegPair length_arg) {
1386   Register tmp_reg = rax;
1387   assert(!body_arg.first()->is_Register() || body_arg.first()->as_Register() != tmp_reg,
1388          "possible collision");
1389   assert(!length_arg.first()->is_Register() || length_arg.first()->as_Register() != tmp_reg,
1390          "possible collision");
1391 
1392   // Pass the length, ptr pair
1393   Label is_null, done;
1394   VMRegPair tmp(tmp_reg->as_VMReg());
1395   if (reg.first()->is_stack()) {
1396     // Load the arg up from the stack
1397     simple_move32(masm, reg, tmp);
1398     reg = tmp;
1399   }
1400   __ testptr(reg.first()->as_Register(), reg.first()->as_Register());
1401   __ jccb(Assembler::equal, is_null);
1402   __ lea(tmp_reg, Address(reg.first()->as_Register(), arrayOopDesc::base_offset_in_bytes(in_elem_type)));
1403   simple_move32(masm, tmp, body_arg);
1404   // load the length relative to the body.
1405   __ movl(tmp_reg, Address(tmp_reg, arrayOopDesc::length_offset_in_bytes() -
1406                            arrayOopDesc::base_offset_in_bytes(in_elem_type)));
1407   simple_move32(masm, tmp, length_arg);
1408   __ jmpb(done);
1409   __ bind(is_null);
1410   // Pass zeros
1411   __ xorptr(tmp_reg, tmp_reg);
1412   simple_move32(masm, tmp, body_arg);
1413   simple_move32(masm, tmp, length_arg);
1414   __ bind(done);
1415 }
1416 
1417 static void verify_oop_args(MacroAssembler* masm,
1418                             const methodHandle& method,
1419                             const BasicType* sig_bt,
1420                             const VMRegPair* regs) {
1421   Register temp_reg = rbx;  // not part of any compiled calling seq
1422   if (VerifyOops) {
1423     for (int i = 0; i < method->size_of_parameters(); i++) {
1424       if (sig_bt[i] == T_OBJECT ||
1425           sig_bt[i] == T_ARRAY) {
1426         VMReg r = regs[i].first();
1427         assert(r->is_valid(), "bad oop arg");
1428         if (r->is_stack()) {
1429           __ movptr(temp_reg, Address(rsp, r->reg2stack() * VMRegImpl::stack_slot_size + wordSize));
1430           __ verify_oop(temp_reg);
1431         } else {
1432           __ verify_oop(r->as_Register());
1433         }
1434       }
1435     }
1436   }
1437 }
1438 
1439 static void gen_special_dispatch(MacroAssembler* masm,
1440                                  const methodHandle& method,
1441                                  const BasicType* sig_bt,
1442                                  const VMRegPair* regs) {
1443   verify_oop_args(masm, method, sig_bt, regs);
1444   vmIntrinsics::ID iid = method->intrinsic_id();
1445 
1446   // Now write the args into the outgoing interpreter space
1447   bool     has_receiver   = false;
1448   Register receiver_reg   = noreg;
1449   int      member_arg_pos = -1;
1450   Register member_reg     = noreg;
1451   int      ref_kind       = MethodHandles::signature_polymorphic_intrinsic_ref_kind(iid);
1452   if (ref_kind != 0) {
1453     member_arg_pos = method->size_of_parameters() - 1;  // trailing MemberName argument
1454     member_reg = rbx;  // known to be free at this point
1455     has_receiver = MethodHandles::ref_kind_has_receiver(ref_kind);
1456   } else if (iid == vmIntrinsics::_invokeBasic) {
1457     has_receiver = true;
1458   } else {
1459     fatal("unexpected intrinsic id %d", iid);
1460   }
1461 
1462   if (member_reg != noreg) {
1463     // Load the member_arg into register, if necessary.
1464     SharedRuntime::check_member_name_argument_is_last_argument(method, sig_bt, regs);
1465     VMReg r = regs[member_arg_pos].first();
1466     if (r->is_stack()) {
1467       __ movptr(member_reg, Address(rsp, r->reg2stack() * VMRegImpl::stack_slot_size + wordSize));
1468     } else {
1469       // no data motion is needed
1470       member_reg = r->as_Register();
1471     }
1472   }
1473 
1474   if (has_receiver) {
1475     // Make sure the receiver is loaded into a register.
1476     assert(method->size_of_parameters() > 0, "oob");
1477     assert(sig_bt[0] == T_OBJECT, "receiver argument must be an object");
1478     VMReg r = regs[0].first();
1479     assert(r->is_valid(), "bad receiver arg");
1480     if (r->is_stack()) {
1481       // Porting note:  This assumes that compiled calling conventions always
1482       // pass the receiver oop in a register.  If this is not true on some
1483       // platform, pick a temp and load the receiver from stack.
1484       fatal("receiver always in a register");
1485       receiver_reg = rcx;  // known to be free at this point
1486       __ movptr(receiver_reg, Address(rsp, r->reg2stack() * VMRegImpl::stack_slot_size + wordSize));
1487     } else {
1488       // no data motion is needed
1489       receiver_reg = r->as_Register();
1490     }
1491   }
1492 
1493   // Figure out which address we are really jumping to:
1494   MethodHandles::generate_method_handle_dispatch(masm, iid,
1495                                                  receiver_reg, member_reg, /*for_compiler_entry:*/ true);
1496 }
1497 
1498 // ---------------------------------------------------------------------------
1499 // Generate a native wrapper for a given method.  The method takes arguments
1500 // in the Java compiled code convention, marshals them to the native
1501 // convention (handlizes oops, etc), transitions to native, makes the call,
1502 // returns to java state (possibly blocking), unhandlizes any result and
1503 // returns.
1504 //
1505 // Critical native functions are a shorthand for the use of
1506 // GetPrimtiveArrayCritical and disallow the use of any other JNI
1507 // functions.  The wrapper is expected to unpack the arguments before
1508 // passing them to the callee and perform checks before and after the
1509 // native call to ensure that they GCLocker
1510 // lock_critical/unlock_critical semantics are followed.  Some other
1511 // parts of JNI setup are skipped like the tear down of the JNI handle
1512 // block and the check for pending exceptions it's impossible for them
1513 // to be thrown.
1514 //
1515 // They are roughly structured like this:
1516 //    if (GCLocker::needs_gc())
1517 //      SharedRuntime::block_for_jni_critical();
1518 //    tranistion to thread_in_native
1519 //    unpack arrray arguments and call native entry point
1520 //    check for safepoint in progress
1521 //    check if any thread suspend flags are set
1522 //      call into JVM and possible unlock the JNI critical
1523 //      if a GC was suppressed while in the critical native.
1524 //    transition back to thread_in_Java
1525 //    return to caller
1526 //
1527 nmethod* SharedRuntime::generate_native_wrapper(MacroAssembler* masm,
1528                                                 const methodHandle& method,
1529                                                 int compile_id,
1530                                                 BasicType* in_sig_bt,
1531                                                 VMRegPair* in_regs,
1532                                                 BasicType ret_type,
1533                                                 address critical_entry) {
1534   if (method->is_method_handle_intrinsic()) {
1535     vmIntrinsics::ID iid = method->intrinsic_id();
1536     intptr_t start = (intptr_t)__ pc();
1537     int vep_offset = ((intptr_t)__ pc()) - start;
1538     gen_special_dispatch(masm,
1539                          method,
1540                          in_sig_bt,
1541                          in_regs);
1542     int frame_complete = ((intptr_t)__ pc()) - start;  // not complete, period
1543     __ flush();
1544     int stack_slots = SharedRuntime::out_preserve_stack_slots();  // no out slots at all, actually
1545     return nmethod::new_native_nmethod(method,
1546                                        compile_id,
1547                                        masm->code(),
1548                                        vep_offset,
1549                                        frame_complete,
1550                                        stack_slots / VMRegImpl::slots_per_word,
1551                                        in_ByteSize(-1),
1552                                        in_ByteSize(-1),
1553                                        (OopMapSet*)NULL);
1554   }
1555   bool is_critical_native = true;
1556   address native_func = critical_entry;
1557   if (native_func == NULL) {
1558     native_func = method->native_function();
1559     is_critical_native = false;
1560   }
1561   assert(native_func != NULL, "must have function");
1562 
1563   // An OopMap for lock (and class if static)
1564   OopMapSet *oop_maps = new OopMapSet();
1565 
1566   // We have received a description of where all the java arg are located
1567   // on entry to the wrapper. We need to convert these args to where
1568   // the jni function will expect them. To figure out where they go
1569   // we convert the java signature to a C signature by inserting
1570   // the hidden arguments as arg[0] and possibly arg[1] (static method)
1571 
1572   const int total_in_args = method->size_of_parameters();
1573   int total_c_args = total_in_args;
1574   if (!is_critical_native) {
1575     total_c_args += 1;
1576     if (method->is_static()) {
1577       total_c_args++;
1578     }
1579   } else {
1580     for (int i = 0; i < total_in_args; i++) {
1581       if (in_sig_bt[i] == T_ARRAY) {
1582         total_c_args++;
1583       }
1584     }
1585   }
1586 
1587   BasicType* out_sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_c_args);
1588   VMRegPair* out_regs   = NEW_RESOURCE_ARRAY(VMRegPair, total_c_args);
1589   BasicType* in_elem_bt = NULL;
1590 
1591   int argc = 0;
1592   if (!is_critical_native) {
1593     out_sig_bt[argc++] = T_ADDRESS;
1594     if (method->is_static()) {
1595       out_sig_bt[argc++] = T_OBJECT;
1596     }
1597 
1598     for (int i = 0; i < total_in_args ; i++ ) {
1599       out_sig_bt[argc++] = in_sig_bt[i];
1600     }
1601   } else {
1602     Thread* THREAD = Thread::current();
1603     in_elem_bt = NEW_RESOURCE_ARRAY(BasicType, total_in_args);
1604     SignatureStream ss(method->signature());
1605     for (int i = 0; i < total_in_args ; i++ ) {
1606       if (in_sig_bt[i] == T_ARRAY) {
1607         // Arrays are passed as int, elem* pair
1608         out_sig_bt[argc++] = T_INT;
1609         out_sig_bt[argc++] = T_ADDRESS;
1610         Symbol* atype = ss.as_symbol(CHECK_NULL);
1611         const char* at = atype->as_C_string();
1612         if (strlen(at) == 2) {
1613           assert(at[0] == '[', "must be");
1614           switch (at[1]) {
1615             case 'B': in_elem_bt[i]  = T_BYTE; break;
1616             case 'C': in_elem_bt[i]  = T_CHAR; break;
1617             case 'D': in_elem_bt[i]  = T_DOUBLE; break;
1618             case 'F': in_elem_bt[i]  = T_FLOAT; break;
1619             case 'I': in_elem_bt[i]  = T_INT; break;
1620             case 'J': in_elem_bt[i]  = T_LONG; break;
1621             case 'S': in_elem_bt[i]  = T_SHORT; break;
1622             case 'Z': in_elem_bt[i]  = T_BOOLEAN; break;
1623             default: ShouldNotReachHere();
1624           }
1625         }
1626       } else {
1627         out_sig_bt[argc++] = in_sig_bt[i];
1628         in_elem_bt[i] = T_VOID;
1629       }
1630       if (in_sig_bt[i] != T_VOID) {
1631         assert(in_sig_bt[i] == ss.type(), "must match");
1632         ss.next();
1633       }
1634     }
1635   }
1636 
1637   // Now figure out where the args must be stored and how much stack space
1638   // they require.
1639   int out_arg_slots;
1640   out_arg_slots = c_calling_convention(out_sig_bt, out_regs, NULL, total_c_args);
1641 
1642   // Compute framesize for the wrapper.  We need to handlize all oops in
1643   // registers a max of 2 on x86.
1644 
1645   // Calculate the total number of stack slots we will need.
1646 
1647   // First count the abi requirement plus all of the outgoing args
1648   int stack_slots = SharedRuntime::out_preserve_stack_slots() + out_arg_slots;
1649 
1650   // Now the space for the inbound oop handle area
1651   int total_save_slots = 2 * VMRegImpl::slots_per_word; // 2 arguments passed in registers
1652   if (is_critical_native) {
1653     // Critical natives may have to call out so they need a save area
1654     // for register arguments.
1655     int double_slots = 0;
1656     int single_slots = 0;
1657     for ( int i = 0; i < total_in_args; i++) {
1658       if (in_regs[i].first()->is_Register()) {
1659         const Register reg = in_regs[i].first()->as_Register();
1660         switch (in_sig_bt[i]) {
1661           case T_ARRAY:  // critical array (uses 2 slots on LP64)
1662           case T_BOOLEAN:
1663           case T_BYTE:
1664           case T_SHORT:
1665           case T_CHAR:
1666           case T_INT:  single_slots++; break;
1667           case T_LONG: double_slots++; break;
1668           default:  ShouldNotReachHere();
1669         }
1670       } else if (in_regs[i].first()->is_XMMRegister()) {
1671         switch (in_sig_bt[i]) {
1672           case T_FLOAT:  single_slots++; break;
1673           case T_DOUBLE: double_slots++; break;
1674           default:  ShouldNotReachHere();
1675         }
1676       } else if (in_regs[i].first()->is_FloatRegister()) {
1677         ShouldNotReachHere();
1678       }
1679     }
1680     total_save_slots = double_slots * 2 + single_slots;
1681     // align the save area
1682     if (double_slots != 0) {
1683       stack_slots = align_up(stack_slots, 2);
1684     }
1685   }
1686 
1687   int oop_handle_offset = stack_slots;
1688   stack_slots += total_save_slots;
1689 
1690   // Now any space we need for handlizing a klass if static method
1691 
1692   int klass_slot_offset = 0;
1693   int klass_offset = -1;
1694   int lock_slot_offset = 0;
1695   bool is_static = false;
1696 
1697   if (method->is_static()) {
1698     klass_slot_offset = stack_slots;
1699     stack_slots += VMRegImpl::slots_per_word;
1700     klass_offset = klass_slot_offset * VMRegImpl::stack_slot_size;
1701     is_static = true;
1702   }
1703 
1704   // Plus a lock if needed
1705 
1706   if (method->is_synchronized()) {
1707     lock_slot_offset = stack_slots;
1708     stack_slots += VMRegImpl::slots_per_word;
1709   }
1710 
1711   // Now a place (+2) to save return values or temp during shuffling
1712   // + 2 for return address (which we own) and saved rbp,
1713   stack_slots += 4;
1714 
1715   // Ok The space we have allocated will look like:
1716   //
1717   //
1718   // FP-> |                     |
1719   //      |---------------------|
1720   //      | 2 slots for moves   |
1721   //      |---------------------|
1722   //      | lock box (if sync)  |
1723   //      |---------------------| <- lock_slot_offset  (-lock_slot_rbp_offset)
1724   //      | klass (if static)   |
1725   //      |---------------------| <- klass_slot_offset
1726   //      | oopHandle area      |
1727   //      |---------------------| <- oop_handle_offset (a max of 2 registers)
1728   //      | outbound memory     |
1729   //      | based arguments     |
1730   //      |                     |
1731   //      |---------------------|
1732   //      |                     |
1733   // SP-> | out_preserved_slots |
1734   //
1735   //
1736   // ****************************************************************************
1737   // WARNING - on Windows Java Natives use pascal calling convention and pop the
1738   // arguments off of the stack after the jni call. Before the call we can use
1739   // instructions that are SP relative. After the jni call we switch to FP
1740   // relative instructions instead of re-adjusting the stack on windows.
1741   // ****************************************************************************
1742 
1743 
1744   // Now compute actual number of stack words we need rounding to make
1745   // stack properly aligned.
1746   stack_slots = align_up(stack_slots, StackAlignmentInSlots);
1747 
1748   int stack_size = stack_slots * VMRegImpl::stack_slot_size;
1749 
1750   intptr_t start = (intptr_t)__ pc();
1751 
1752   // First thing make an ic check to see if we should even be here
1753 
1754   // We are free to use all registers as temps without saving them and
1755   // restoring them except rbp. rbp is the only callee save register
1756   // as far as the interpreter and the compiler(s) are concerned.
1757 
1758 
1759   const Register ic_reg = rax;
1760   const Register receiver = rcx;
1761   Label hit;
1762   Label exception_pending;
1763 
1764   __ verify_oop(receiver);
1765   __ cmpptr(ic_reg, Address(receiver, oopDesc::klass_offset_in_bytes()));
1766   __ jcc(Assembler::equal, hit);
1767 
1768   __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
1769 
1770   // verified entry must be aligned for code patching.
1771   // and the first 5 bytes must be in the same cache line
1772   // if we align at 8 then we will be sure 5 bytes are in the same line
1773   __ align(8);
1774 
1775   __ bind(hit);
1776 
1777   int vep_offset = ((intptr_t)__ pc()) - start;
1778 
1779 #ifdef COMPILER1
1780   // For Object.hashCode, System.identityHashCode try to pull hashCode from object header if available.
1781   if ((InlineObjectHash && method->intrinsic_id() == vmIntrinsics::_hashCode) || (method->intrinsic_id() == vmIntrinsics::_identityHashCode)) {
1782     inline_check_hashcode_from_object_header(masm, method, rcx /*obj_reg*/, rax /*result*/);
1783    }
1784 #endif // COMPILER1
1785 
1786   // The instruction at the verified entry point must be 5 bytes or longer
1787   // because it can be patched on the fly by make_non_entrant. The stack bang
1788   // instruction fits that requirement.
1789 
1790   // Generate stack overflow check
1791 
1792   if (UseStackBanging) {
1793     __ bang_stack_with_offset((int)JavaThread::stack_shadow_zone_size());
1794   } else {
1795     // need a 5 byte instruction to allow MT safe patching to non-entrant
1796     __ fat_nop();
1797   }
1798 
1799   // Generate a new frame for the wrapper.
1800   __ enter();
1801   // -2 because return address is already present and so is saved rbp
1802   __ subptr(rsp, stack_size - 2*wordSize);
1803 
1804   // Frame is now completed as far as size and linkage.
1805   int frame_complete = ((intptr_t)__ pc()) - start;
1806 
1807   if (UseRTMLocking) {
1808     // Abort RTM transaction before calling JNI
1809     // because critical section will be large and will be
1810     // aborted anyway. Also nmethod could be deoptimized.
1811     __ xabort(0);
1812   }
1813 
1814   // Calculate the difference between rsp and rbp,. We need to know it
1815   // after the native call because on windows Java Natives will pop
1816   // the arguments and it is painful to do rsp relative addressing
1817   // in a platform independent way. So after the call we switch to
1818   // rbp, relative addressing.
1819 
1820   int fp_adjustment = stack_size - 2*wordSize;
1821 
1822 #ifdef COMPILER2
1823   // C2 may leave the stack dirty if not in SSE2+ mode
1824   if (UseSSE >= 2) {
1825     __ verify_FPU(0, "c2i transition should have clean FPU stack");
1826   } else {
1827     __ empty_FPU_stack();
1828   }
1829 #endif /* COMPILER2 */
1830 
1831   // Compute the rbp, offset for any slots used after the jni call
1832 
1833   int lock_slot_rbp_offset = (lock_slot_offset*VMRegImpl::stack_slot_size) - fp_adjustment;
1834 
1835   // We use rdi as a thread pointer because it is callee save and
1836   // if we load it once it is usable thru the entire wrapper
1837   const Register thread = rdi;
1838 
1839   // We use rsi as the oop handle for the receiver/klass
1840   // It is callee save so it survives the call to native
1841 
1842   const Register oop_handle_reg = rsi;
1843 
1844   __ get_thread(thread);
1845 
1846   if (is_critical_native SHENANDOAHGC_ONLY(&& !UseShenandoahGC)) {
1847     check_needs_gc_for_critical_native(masm, thread, stack_slots, total_c_args, total_in_args,
1848                                        oop_handle_offset, oop_maps, in_regs, in_sig_bt);
1849   }
1850 
1851   //
1852   // We immediately shuffle the arguments so that any vm call we have to
1853   // make from here on out (sync slow path, jvmti, etc.) we will have
1854   // captured the oops from our caller and have a valid oopMap for
1855   // them.
1856 
1857   // -----------------
1858   // The Grand Shuffle
1859   //
1860   // Natives require 1 or 2 extra arguments over the normal ones: the JNIEnv*
1861   // and, if static, the class mirror instead of a receiver.  This pretty much
1862   // guarantees that register layout will not match (and x86 doesn't use reg
1863   // parms though amd does).  Since the native abi doesn't use register args
1864   // and the java conventions does we don't have to worry about collisions.
1865   // All of our moved are reg->stack or stack->stack.
1866   // We ignore the extra arguments during the shuffle and handle them at the
1867   // last moment. The shuffle is described by the two calling convention
1868   // vectors we have in our possession. We simply walk the java vector to
1869   // get the source locations and the c vector to get the destinations.
1870 
1871   int c_arg = is_critical_native ? 0 : (method->is_static() ? 2 : 1 );
1872 
1873   // Record rsp-based slot for receiver on stack for non-static methods
1874   int receiver_offset = -1;
1875 
1876   // This is a trick. We double the stack slots so we can claim
1877   // the oops in the caller's frame. Since we are sure to have
1878   // more args than the caller doubling is enough to make
1879   // sure we can capture all the incoming oop args from the
1880   // caller.
1881   //
1882   OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1883 
1884 #if INCLUDE_SHENANDOAHGC
1885   // Inbound arguments that need to be pinned for critical natives
1886   GrowableArray<int> pinned_args(total_in_args);
1887   // Current stack slot for storing register based array argument
1888   int pinned_slot = oop_handle_offset;
1889 #endif
1890   // Mark location of rbp,
1891   // map->set_callee_saved(VMRegImpl::stack2reg( stack_slots - 2), stack_slots * 2, 0, rbp->as_VMReg());
1892 
1893   // We know that we only have args in at most two integer registers (rcx, rdx). So rax, rbx
1894   // Are free to temporaries if we have to do  stack to steck moves.
1895   // All inbound args are referenced based on rbp, and all outbound args via rsp.
1896 
1897   for (int i = 0; i < total_in_args ; i++, c_arg++ ) {
1898     switch (in_sig_bt[i]) {
1899       case T_ARRAY:
1900         if (is_critical_native) {
1901 #if INCLUDE_SHENANDOAHGC
1902           VMRegPair in_arg = in_regs[i];
1903           if (UseShenandoahGC) {
1904             // gen_pin_object handles save and restore
1905             // of any clobbered registers
1906             ShenandoahBarrierSet::assembler()->gen_pin_object(masm, thread, in_arg);
1907             pinned_args.append(i);
1908 
1909             // rax has pinned array
1910             VMRegPair result_reg(rax->as_VMReg());
1911             if (!in_arg.first()->is_stack()) {
1912               assert(pinned_slot <= stack_slots, "overflow");
1913               simple_move32(masm, result_reg, VMRegImpl::stack2reg(pinned_slot));
1914               pinned_slot += VMRegImpl::slots_per_word;
1915             } else {
1916               // Write back pinned value, it will be used to unpin this argument
1917               __ movptr(Address(rbp, reg2offset_in(in_arg.first())), result_reg.first()->as_Register());
1918             }
1919             // We have the array in register, use it
1920             in_arg = result_reg;
1921           }
1922           unpack_array_argument(masm, in_arg, in_elem_bt[i], out_regs[c_arg + 1], out_regs[c_arg]);
1923 #else
1924           unpack_array_argument(masm, in_regs[i], in_elem_bt[i], out_regs[c_arg + 1], out_regs[c_arg]);
1925 #endif
1926           c_arg++;
1927           break;
1928         }
1929       case T_OBJECT:
1930         assert(!is_critical_native, "no oop arguments");
1931         object_move(masm, map, oop_handle_offset, stack_slots, in_regs[i], out_regs[c_arg],
1932                     ((i == 0) && (!is_static)),
1933                     &receiver_offset);
1934         break;
1935       case T_VOID:
1936         break;
1937 
1938       case T_FLOAT:
1939         float_move(masm, in_regs[i], out_regs[c_arg]);
1940           break;
1941 
1942       case T_DOUBLE:
1943         assert( i + 1 < total_in_args &&
1944                 in_sig_bt[i + 1] == T_VOID &&
1945                 out_sig_bt[c_arg+1] == T_VOID, "bad arg list");
1946         double_move(masm, in_regs[i], out_regs[c_arg]);
1947         break;
1948 
1949       case T_LONG :
1950         long_move(masm, in_regs[i], out_regs[c_arg]);
1951         break;
1952 
1953       case T_ADDRESS: assert(false, "found T_ADDRESS in java args");
1954 
1955       default:
1956         simple_move32(masm, in_regs[i], out_regs[c_arg]);
1957     }
1958   }
1959 
1960   // Pre-load a static method's oop into rsi.  Used both by locking code and
1961   // the normal JNI call code.
1962   if (method->is_static() && !is_critical_native) {
1963 
1964     //  load opp into a register
1965     __ movoop(oop_handle_reg, JNIHandles::make_local(method->method_holder()->java_mirror()));
1966 
1967     // Now handlize the static class mirror it's known not-null.
1968     __ movptr(Address(rsp, klass_offset), oop_handle_reg);
1969     map->set_oop(VMRegImpl::stack2reg(klass_slot_offset));
1970 
1971     // Now get the handle
1972     __ lea(oop_handle_reg, Address(rsp, klass_offset));
1973     // store the klass handle as second argument
1974     __ movptr(Address(rsp, wordSize), oop_handle_reg);
1975   }
1976 
1977   // Change state to native (we save the return address in the thread, since it might not
1978   // be pushed on the stack when we do a a stack traversal). It is enough that the pc()
1979   // points into the right code segment. It does not have to be the correct return pc.
1980   // We use the same pc/oopMap repeatedly when we call out
1981 
1982   intptr_t the_pc = (intptr_t) __ pc();
1983   oop_maps->add_gc_map(the_pc - start, map);
1984 
1985   __ set_last_Java_frame(thread, rsp, noreg, (address)the_pc);
1986 
1987 
1988   // We have all of the arguments setup at this point. We must not touch any register
1989   // argument registers at this point (what if we save/restore them there are no oop?
1990 
1991   {
1992     SkipIfEqual skip_if(masm, &DTraceMethodProbes, 0);
1993     __ mov_metadata(rax, method());
1994     __ call_VM_leaf(
1995          CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry),
1996          thread, rax);
1997   }
1998 
1999   // RedefineClasses() tracing support for obsolete method entry
2000   if (log_is_enabled(Trace, redefine, class, obsolete)) {
2001     __ mov_metadata(rax, method());
2002     __ call_VM_leaf(
2003          CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
2004          thread, rax);
2005   }
2006 
2007   // These are register definitions we need for locking/unlocking
2008   const Register swap_reg = rax;  // Must use rax, for cmpxchg instruction
2009   const Register obj_reg  = rcx;  // Will contain the oop
2010   const Register lock_reg = rdx;  // Address of compiler lock object (BasicLock)
2011 
2012   Label slow_path_lock;
2013   Label lock_done;
2014 
2015   // Lock a synchronized method
2016   if (method->is_synchronized()) {
2017     assert(!is_critical_native, "unhandled");
2018 
2019 
2020     const int mark_word_offset = BasicLock::displaced_header_offset_in_bytes();
2021 
2022     // Get the handle (the 2nd argument)
2023     __ movptr(oop_handle_reg, Address(rsp, wordSize));
2024 
2025     // Get address of the box
2026 
2027     __ lea(lock_reg, Address(rbp, lock_slot_rbp_offset));
2028 
2029     // Load the oop from the handle
2030     __ movptr(obj_reg, Address(oop_handle_reg, 0));
2031 
2032     if (UseBiasedLocking) {
2033       // Note that oop_handle_reg is trashed during this call
2034       __ biased_locking_enter(lock_reg, obj_reg, swap_reg, oop_handle_reg, false, lock_done, &slow_path_lock);
2035     }
2036 
2037     // Load immediate 1 into swap_reg %rax,
2038     __ movptr(swap_reg, 1);
2039 
2040     // Load (object->mark() | 1) into swap_reg %rax,
2041     __ orptr(swap_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
2042 
2043     // Save (object->mark() | 1) into BasicLock's displaced header
2044     __ movptr(Address(lock_reg, mark_word_offset), swap_reg);
2045 
2046     if (os::is_MP()) {
2047       __ lock();
2048     }
2049 
2050     // src -> dest iff dest == rax, else rax, <- dest
2051     // *obj_reg = lock_reg iff *obj_reg == rax, else rax, = *(obj_reg)
2052     __ cmpxchgptr(lock_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
2053     __ jcc(Assembler::equal, lock_done);
2054 
2055     // Test if the oopMark is an obvious stack pointer, i.e.,
2056     //  1) (mark & 3) == 0, and
2057     //  2) rsp <= mark < mark + os::pagesize()
2058     // These 3 tests can be done by evaluating the following
2059     // expression: ((mark - rsp) & (3 - os::vm_page_size())),
2060     // assuming both stack pointer and pagesize have their
2061     // least significant 2 bits clear.
2062     // NOTE: the oopMark is in swap_reg %rax, as the result of cmpxchg
2063 
2064     __ subptr(swap_reg, rsp);
2065     __ andptr(swap_reg, 3 - os::vm_page_size());
2066 
2067     // Save the test result, for recursive case, the result is zero
2068     __ movptr(Address(lock_reg, mark_word_offset), swap_reg);
2069     __ jcc(Assembler::notEqual, slow_path_lock);
2070     // Slow path will re-enter here
2071     __ bind(lock_done);
2072 
2073     if (UseBiasedLocking) {
2074       // Re-fetch oop_handle_reg as we trashed it above
2075       __ movptr(oop_handle_reg, Address(rsp, wordSize));
2076     }
2077   }
2078 
2079 
2080   // Finally just about ready to make the JNI call
2081 
2082 
2083   // get JNIEnv* which is first argument to native
2084   if (!is_critical_native) {
2085     __ lea(rdx, Address(thread, in_bytes(JavaThread::jni_environment_offset())));
2086     __ movptr(Address(rsp, 0), rdx);
2087   }
2088 
2089   // Now set thread in native
2090   __ movl(Address(thread, JavaThread::thread_state_offset()), _thread_in_native);
2091 
2092   __ call(RuntimeAddress(native_func));
2093 
2094   // Verify or restore cpu control state after JNI call
2095   __ restore_cpu_control_state_after_jni();
2096 
2097   // WARNING - on Windows Java Natives use pascal calling convention and pop the
2098   // arguments off of the stack. We could just re-adjust the stack pointer here
2099   // and continue to do SP relative addressing but we instead switch to FP
2100   // relative addressing.
2101 
2102   // Unpack native results.
2103   switch (ret_type) {
2104   case T_BOOLEAN: __ c2bool(rax);            break;
2105   case T_CHAR   : __ andptr(rax, 0xFFFF);    break;
2106   case T_BYTE   : __ sign_extend_byte (rax); break;
2107   case T_SHORT  : __ sign_extend_short(rax); break;
2108   case T_INT    : /* nothing to do */        break;
2109   case T_DOUBLE :
2110   case T_FLOAT  :
2111     // Result is in st0 we'll save as needed
2112     break;
2113   case T_ARRAY:                 // Really a handle
2114   case T_OBJECT:                // Really a handle
2115       break; // can't de-handlize until after safepoint check
2116   case T_VOID: break;
2117   case T_LONG: break;
2118   default       : ShouldNotReachHere();
2119   }
2120 
2121 #if INCLUDE_SHENANDOAHGC
2122   if (UseShenandoahGC) {
2123     // unpin pinned arguments
2124     pinned_slot = oop_handle_offset;
2125     if (pinned_args.length() > 0) {
2126       // save return value that may be overwritten otherwise.
2127       save_native_result(masm, ret_type, stack_slots);
2128       for (int index = 0; index < pinned_args.length(); index ++) {
2129         int i = pinned_args.at(index);
2130         assert(pinned_slot <= stack_slots, "overflow");
2131         if (!in_regs[i].first()->is_stack()) {
2132           int offset = pinned_slot * VMRegImpl::stack_slot_size;
2133           __ movl(in_regs[i].first()->as_Register(), Address(rsp, offset));
2134           pinned_slot += VMRegImpl::slots_per_word;
2135         }
2136         // gen_pin_object handles save and restore
2137         // of any other clobbered registers
2138         ShenandoahBarrierSet::assembler()->gen_unpin_object(masm, thread, in_regs[i]);
2139       }
2140       restore_native_result(masm, ret_type, stack_slots);
2141     }
2142   }
2143 #endif
2144   // Switch thread to "native transition" state before reading the synchronization state.
2145   // This additional state is necessary because reading and testing the synchronization
2146   // state is not atomic w.r.t. GC, as this scenario demonstrates:
2147   //     Java thread A, in _thread_in_native state, loads _not_synchronized and is preempted.
2148   //     VM thread changes sync state to synchronizing and suspends threads for GC.
2149   //     Thread A is resumed to finish this native method, but doesn't block here since it
2150   //     didn't see any synchronization is progress, and escapes.
2151   __ movl(Address(thread, JavaThread::thread_state_offset()), _thread_in_native_trans);
2152 
2153   if(os::is_MP()) {
2154     if (UseMembar) {
2155       // Force this write out before the read below
2156       __ membar(Assembler::Membar_mask_bits(
2157            Assembler::LoadLoad | Assembler::LoadStore |
2158            Assembler::StoreLoad | Assembler::StoreStore));
2159     } else {
2160       // Write serialization page so VM thread can do a pseudo remote membar.
2161       // We use the current thread pointer to calculate a thread specific
2162       // offset to write to within the page. This minimizes bus traffic
2163       // due to cache line collision.
2164       __ serialize_memory(thread, rcx);
2165     }
2166   }
2167 
2168   if (AlwaysRestoreFPU) {
2169     // Make sure the control word is correct.
2170     __ fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_std()));
2171   }
2172 
2173   Label after_transition;
2174 
2175   // check for safepoint operation in progress and/or pending suspend requests
2176   { Label Continue, slow_path;
2177 
2178     __ safepoint_poll(slow_path, thread, noreg);
2179 
2180     __ cmpl(Address(thread, JavaThread::suspend_flags_offset()), 0);
2181     __ jcc(Assembler::equal, Continue);
2182     __ bind(slow_path);
2183 
2184     // Don't use call_VM as it will see a possible pending exception and forward it
2185     // and never return here preventing us from clearing _last_native_pc down below.
2186     // Also can't use call_VM_leaf either as it will check to see if rsi & rdi are
2187     // preserved and correspond to the bcp/locals pointers. So we do a runtime call
2188     // by hand.
2189     //
2190     __ vzeroupper();
2191 
2192     save_native_result(masm, ret_type, stack_slots);
2193     __ push(thread);
2194     if (!is_critical_native) {
2195       __ call(RuntimeAddress(CAST_FROM_FN_PTR(address,
2196                                               JavaThread::check_special_condition_for_native_trans)));
2197     } else {
2198       __ call(RuntimeAddress(CAST_FROM_FN_PTR(address,
2199                                               JavaThread::check_special_condition_for_native_trans_and_transition)));
2200     }
2201     __ increment(rsp, wordSize);
2202     // Restore any method result value
2203     restore_native_result(masm, ret_type, stack_slots);
2204 
2205     if (is_critical_native) {
2206       // The call above performed the transition to thread_in_Java so
2207       // skip the transition logic below.
2208       __ jmpb(after_transition);
2209     }
2210 
2211     __ bind(Continue);
2212   }
2213 
2214   // change thread state
2215   __ movl(Address(thread, JavaThread::thread_state_offset()), _thread_in_Java);
2216   __ bind(after_transition);
2217 
2218   Label reguard;
2219   Label reguard_done;
2220   __ cmpl(Address(thread, JavaThread::stack_guard_state_offset()), JavaThread::stack_guard_yellow_reserved_disabled);
2221   __ jcc(Assembler::equal, reguard);
2222 
2223   // slow path reguard  re-enters here
2224   __ bind(reguard_done);
2225 
2226   // Handle possible exception (will unlock if necessary)
2227 
2228   // native result if any is live
2229 
2230   // Unlock
2231   Label slow_path_unlock;
2232   Label unlock_done;
2233   if (method->is_synchronized()) {
2234 
2235     Label done;
2236 
2237     // Get locked oop from the handle we passed to jni
2238     __ movptr(obj_reg, Address(oop_handle_reg, 0));
2239 
2240     if (UseBiasedLocking) {
2241       __ biased_locking_exit(obj_reg, rbx, done);
2242     }
2243 
2244     // Simple recursive lock?
2245 
2246     __ cmpptr(Address(rbp, lock_slot_rbp_offset), (int32_t)NULL_WORD);
2247     __ jcc(Assembler::equal, done);
2248 
2249     // Must save rax, if if it is live now because cmpxchg must use it
2250     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
2251       save_native_result(masm, ret_type, stack_slots);
2252     }
2253 
2254     //  get old displaced header
2255     __ movptr(rbx, Address(rbp, lock_slot_rbp_offset));
2256 
2257     // get address of the stack lock
2258     __ lea(rax, Address(rbp, lock_slot_rbp_offset));
2259 
2260     // Atomic swap old header if oop still contains the stack lock
2261     if (os::is_MP()) {
2262     __ lock();
2263     }
2264 
2265     // src -> dest iff dest == rax, else rax, <- dest
2266     // *obj_reg = rbx, iff *obj_reg == rax, else rax, = *(obj_reg)
2267     __ cmpxchgptr(rbx, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
2268     __ jcc(Assembler::notEqual, slow_path_unlock);
2269 
2270     // slow path re-enters here
2271     __ bind(unlock_done);
2272     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
2273       restore_native_result(masm, ret_type, stack_slots);
2274     }
2275 
2276     __ bind(done);
2277 
2278   }
2279 
2280   {
2281     SkipIfEqual skip_if(masm, &DTraceMethodProbes, 0);
2282     // Tell dtrace about this method exit
2283     save_native_result(masm, ret_type, stack_slots);
2284     __ mov_metadata(rax, method());
2285     __ call_VM_leaf(
2286          CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit),
2287          thread, rax);
2288     restore_native_result(masm, ret_type, stack_slots);
2289   }
2290 
2291   // We can finally stop using that last_Java_frame we setup ages ago
2292 
2293   __ reset_last_Java_frame(thread, false);
2294 
2295   // Unbox oop result, e.g. JNIHandles::resolve value.
2296   if (ret_type == T_OBJECT || ret_type == T_ARRAY) {
2297     __ resolve_jobject(rax /* value */,
2298                        thread /* thread */,
2299                        rcx /* tmp */);
2300   }
2301 
2302   if (CheckJNICalls) {
2303     // clear_pending_jni_exception_check
2304     __ movptr(Address(thread, JavaThread::pending_jni_exception_check_fn_offset()), NULL_WORD);
2305   }
2306 
2307   if (!is_critical_native) {
2308     // reset handle block
2309     __ movptr(rcx, Address(thread, JavaThread::active_handles_offset()));
2310     __ movl(Address(rcx, JNIHandleBlock::top_offset_in_bytes()), NULL_WORD);
2311 
2312     // Any exception pending?
2313     __ cmpptr(Address(thread, in_bytes(Thread::pending_exception_offset())), (int32_t)NULL_WORD);
2314     __ jcc(Assembler::notEqual, exception_pending);
2315   }
2316 
2317   // no exception, we're almost done
2318 
2319   // check that only result value is on FPU stack
2320   __ verify_FPU(ret_type == T_FLOAT || ret_type == T_DOUBLE ? 1 : 0, "native_wrapper normal exit");
2321 
2322   // Fixup floating pointer results so that result looks like a return from a compiled method
2323   if (ret_type == T_FLOAT) {
2324     if (UseSSE >= 1) {
2325       // Pop st0 and store as float and reload into xmm register
2326       __ fstp_s(Address(rbp, -4));
2327       __ movflt(xmm0, Address(rbp, -4));
2328     }
2329   } else if (ret_type == T_DOUBLE) {
2330     if (UseSSE >= 2) {
2331       // Pop st0 and store as double and reload into xmm register
2332       __ fstp_d(Address(rbp, -8));
2333       __ movdbl(xmm0, Address(rbp, -8));
2334     }
2335   }
2336 
2337   // Return
2338 
2339   __ leave();
2340   __ ret(0);
2341 
2342   // Unexpected paths are out of line and go here
2343 
2344   // Slow path locking & unlocking
2345   if (method->is_synchronized()) {
2346 
2347     // BEGIN Slow path lock
2348 
2349     __ bind(slow_path_lock);
2350 
2351     // has last_Java_frame setup. No exceptions so do vanilla call not call_VM
2352     // args are (oop obj, BasicLock* lock, JavaThread* thread)
2353     __ push(thread);
2354     __ push(lock_reg);
2355     __ push(obj_reg);
2356     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_locking_C)));
2357     __ addptr(rsp, 3*wordSize);
2358 
2359 #ifdef ASSERT
2360     { Label L;
2361     __ cmpptr(Address(thread, in_bytes(Thread::pending_exception_offset())), (int)NULL_WORD);
2362     __ jcc(Assembler::equal, L);
2363     __ stop("no pending exception allowed on exit from monitorenter");
2364     __ bind(L);
2365     }
2366 #endif
2367     __ jmp(lock_done);
2368 
2369     // END Slow path lock
2370 
2371     // BEGIN Slow path unlock
2372     __ bind(slow_path_unlock);
2373     __ vzeroupper();
2374     // Slow path unlock
2375 
2376     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2377       save_native_result(masm, ret_type, stack_slots);
2378     }
2379     // Save pending exception around call to VM (which contains an EXCEPTION_MARK)
2380 
2381     __ pushptr(Address(thread, in_bytes(Thread::pending_exception_offset())));
2382     __ movptr(Address(thread, in_bytes(Thread::pending_exception_offset())), NULL_WORD);
2383 
2384 
2385     // should be a peal
2386     // +wordSize because of the push above
2387     // args are (oop obj, BasicLock* lock, JavaThread* thread)
2388     __ push(thread);
2389     __ lea(rax, Address(rbp, lock_slot_rbp_offset));
2390     __ push(rax);
2391 
2392     __ push(obj_reg);
2393     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C)));
2394     __ addptr(rsp, 3*wordSize);
2395 #ifdef ASSERT
2396     {
2397       Label L;
2398       __ cmpptr(Address(thread, in_bytes(Thread::pending_exception_offset())), (int32_t)NULL_WORD);
2399       __ jcc(Assembler::equal, L);
2400       __ stop("no pending exception allowed on exit complete_monitor_unlocking_C");
2401       __ bind(L);
2402     }
2403 #endif /* ASSERT */
2404 
2405     __ popptr(Address(thread, in_bytes(Thread::pending_exception_offset())));
2406 
2407     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2408       restore_native_result(masm, ret_type, stack_slots);
2409     }
2410     __ jmp(unlock_done);
2411     // END Slow path unlock
2412 
2413   }
2414 
2415   // SLOW PATH Reguard the stack if needed
2416 
2417   __ bind(reguard);
2418   __ vzeroupper();
2419   save_native_result(masm, ret_type, stack_slots);
2420   {
2421     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages)));
2422   }
2423   restore_native_result(masm, ret_type, stack_slots);
2424   __ jmp(reguard_done);
2425 
2426 
2427   // BEGIN EXCEPTION PROCESSING
2428 
2429   if (!is_critical_native) {
2430     // Forward  the exception
2431     __ bind(exception_pending);
2432 
2433     // remove possible return value from FPU register stack
2434     __ empty_FPU_stack();
2435 
2436     // pop our frame
2437     __ leave();
2438     // and forward the exception
2439     __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2440   }
2441 
2442   __ flush();
2443 
2444   nmethod *nm = nmethod::new_native_nmethod(method,
2445                                             compile_id,
2446                                             masm->code(),
2447                                             vep_offset,
2448                                             frame_complete,
2449                                             stack_slots / VMRegImpl::slots_per_word,
2450                                             (is_static ? in_ByteSize(klass_offset) : in_ByteSize(receiver_offset)),
2451                                             in_ByteSize(lock_slot_offset*VMRegImpl::stack_slot_size),
2452                                             oop_maps);
2453 
2454   if (is_critical_native) {
2455     nm->set_lazy_critical_native(true);
2456   }
2457 
2458   return nm;
2459 
2460 }
2461 
2462 // this function returns the adjust size (in number of words) to a c2i adapter
2463 // activation for use during deoptimization
2464 int Deoptimization::last_frame_adjust(int callee_parameters, int callee_locals ) {
2465   return (callee_locals - callee_parameters) * Interpreter::stackElementWords;
2466 }
2467 
2468 
2469 uint SharedRuntime::out_preserve_stack_slots() {
2470   return 0;
2471 }
2472 
2473 //------------------------------generate_deopt_blob----------------------------
2474 void SharedRuntime::generate_deopt_blob() {
2475   // allocate space for the code
2476   ResourceMark rm;
2477   // setup code generation tools
2478   // note: the buffer code size must account for StackShadowPages=50
2479   CodeBuffer   buffer("deopt_blob", 1536, 1024);
2480   MacroAssembler* masm = new MacroAssembler(&buffer);
2481   int frame_size_in_words;
2482   OopMap* map = NULL;
2483   // Account for the extra args we place on the stack
2484   // by the time we call fetch_unroll_info
2485   const int additional_words = 2; // deopt kind, thread
2486 
2487   OopMapSet *oop_maps = new OopMapSet();
2488 
2489   // -------------
2490   // This code enters when returning to a de-optimized nmethod.  A return
2491   // address has been pushed on the the stack, and return values are in
2492   // registers.
2493   // If we are doing a normal deopt then we were called from the patched
2494   // nmethod from the point we returned to the nmethod. So the return
2495   // address on the stack is wrong by NativeCall::instruction_size
2496   // We will adjust the value to it looks like we have the original return
2497   // address on the stack (like when we eagerly deoptimized).
2498   // In the case of an exception pending with deoptimized then we enter
2499   // with a return address on the stack that points after the call we patched
2500   // into the exception handler. We have the following register state:
2501   //    rax,: exception
2502   //    rbx,: exception handler
2503   //    rdx: throwing pc
2504   // So in this case we simply jam rdx into the useless return address and
2505   // the stack looks just like we want.
2506   //
2507   // At this point we need to de-opt.  We save the argument return
2508   // registers.  We call the first C routine, fetch_unroll_info().  This
2509   // routine captures the return values and returns a structure which
2510   // describes the current frame size and the sizes of all replacement frames.
2511   // The current frame is compiled code and may contain many inlined
2512   // functions, each with their own JVM state.  We pop the current frame, then
2513   // push all the new frames.  Then we call the C routine unpack_frames() to
2514   // populate these frames.  Finally unpack_frames() returns us the new target
2515   // address.  Notice that callee-save registers are BLOWN here; they have
2516   // already been captured in the vframeArray at the time the return PC was
2517   // patched.
2518   address start = __ pc();
2519   Label cont;
2520 
2521   // Prolog for non exception case!
2522 
2523   // Save everything in sight.
2524 
2525   map = RegisterSaver::save_live_registers(masm, additional_words, &frame_size_in_words, false);
2526   // Normal deoptimization
2527   __ push(Deoptimization::Unpack_deopt);
2528   __ jmp(cont);
2529 
2530   int reexecute_offset = __ pc() - start;
2531 
2532   // Reexecute case
2533   // return address is the pc describes what bci to do re-execute at
2534 
2535   // No need to update map as each call to save_live_registers will produce identical oopmap
2536   (void) RegisterSaver::save_live_registers(masm, additional_words, &frame_size_in_words, false);
2537 
2538   __ push(Deoptimization::Unpack_reexecute);
2539   __ jmp(cont);
2540 
2541   int exception_offset = __ pc() - start;
2542 
2543   // Prolog for exception case
2544 
2545   // all registers are dead at this entry point, except for rax, and
2546   // rdx which contain the exception oop and exception pc
2547   // respectively.  Set them in TLS and fall thru to the
2548   // unpack_with_exception_in_tls entry point.
2549 
2550   __ get_thread(rdi);
2551   __ movptr(Address(rdi, JavaThread::exception_pc_offset()), rdx);
2552   __ movptr(Address(rdi, JavaThread::exception_oop_offset()), rax);
2553 
2554   int exception_in_tls_offset = __ pc() - start;
2555 
2556   // new implementation because exception oop is now passed in JavaThread
2557 
2558   // Prolog for exception case
2559   // All registers must be preserved because they might be used by LinearScan
2560   // Exceptiop oop and throwing PC are passed in JavaThread
2561   // tos: stack at point of call to method that threw the exception (i.e. only
2562   // args are on the stack, no return address)
2563 
2564   // make room on stack for the return address
2565   // It will be patched later with the throwing pc. The correct value is not
2566   // available now because loading it from memory would destroy registers.
2567   __ push(0);
2568 
2569   // Save everything in sight.
2570 
2571   // No need to update map as each call to save_live_registers will produce identical oopmap
2572   (void) RegisterSaver::save_live_registers(masm, additional_words, &frame_size_in_words, false);
2573 
2574   // Now it is safe to overwrite any register
2575 
2576   // store the correct deoptimization type
2577   __ push(Deoptimization::Unpack_exception);
2578 
2579   // load throwing pc from JavaThread and patch it as the return address
2580   // of the current frame. Then clear the field in JavaThread
2581   __ get_thread(rdi);
2582   __ movptr(rdx, Address(rdi, JavaThread::exception_pc_offset()));
2583   __ movptr(Address(rbp, wordSize), rdx);
2584   __ movptr(Address(rdi, JavaThread::exception_pc_offset()), NULL_WORD);
2585 
2586 #ifdef ASSERT
2587   // verify that there is really an exception oop in JavaThread
2588   __ movptr(rax, Address(rdi, JavaThread::exception_oop_offset()));
2589   __ verify_oop(rax);
2590 
2591   // verify that there is no pending exception
2592   Label no_pending_exception;
2593   __ movptr(rax, Address(rdi, Thread::pending_exception_offset()));
2594   __ testptr(rax, rax);
2595   __ jcc(Assembler::zero, no_pending_exception);
2596   __ stop("must not have pending exception here");
2597   __ bind(no_pending_exception);
2598 #endif
2599 
2600   __ bind(cont);
2601 
2602   // Compiled code leaves the floating point stack dirty, empty it.
2603   __ empty_FPU_stack();
2604 
2605 
2606   // Call C code.  Need thread and this frame, but NOT official VM entry
2607   // crud.  We cannot block on this call, no GC can happen.
2608   __ get_thread(rcx);
2609   __ push(rcx);
2610   // fetch_unroll_info needs to call last_java_frame()
2611   __ set_last_Java_frame(rcx, noreg, noreg, NULL);
2612 
2613   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::fetch_unroll_info)));
2614 
2615   // Need to have an oopmap that tells fetch_unroll_info where to
2616   // find any register it might need.
2617 
2618   oop_maps->add_gc_map( __ pc()-start, map);
2619 
2620   // Discard args to fetch_unroll_info
2621   __ pop(rcx);
2622   __ pop(rcx);
2623 
2624   __ get_thread(rcx);
2625   __ reset_last_Java_frame(rcx, false);
2626 
2627   // Load UnrollBlock into EDI
2628   __ mov(rdi, rax);
2629 
2630   // Move the unpack kind to a safe place in the UnrollBlock because
2631   // we are very short of registers
2632 
2633   Address unpack_kind(rdi, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes());
2634   // retrieve the deopt kind from the UnrollBlock.
2635   __ movl(rax, unpack_kind);
2636 
2637    Label noException;
2638   __ cmpl(rax, Deoptimization::Unpack_exception);   // Was exception pending?
2639   __ jcc(Assembler::notEqual, noException);
2640   __ movptr(rax, Address(rcx, JavaThread::exception_oop_offset()));
2641   __ movptr(rdx, Address(rcx, JavaThread::exception_pc_offset()));
2642   __ movptr(Address(rcx, JavaThread::exception_oop_offset()), NULL_WORD);
2643   __ movptr(Address(rcx, JavaThread::exception_pc_offset()), NULL_WORD);
2644 
2645   __ verify_oop(rax);
2646 
2647   // Overwrite the result registers with the exception results.
2648   __ movptr(Address(rsp, RegisterSaver::raxOffset()*wordSize), rax);
2649   __ movptr(Address(rsp, RegisterSaver::rdxOffset()*wordSize), rdx);
2650 
2651   __ bind(noException);
2652 
2653   // Stack is back to only having register save data on the stack.
2654   // Now restore the result registers. Everything else is either dead or captured
2655   // in the vframeArray.
2656 
2657   RegisterSaver::restore_result_registers(masm);
2658 
2659   // Non standard control word may be leaked out through a safepoint blob, and we can
2660   // deopt at a poll point with the non standard control word. However, we should make
2661   // sure the control word is correct after restore_result_registers.
2662   __ fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_std()));
2663 
2664   // All of the register save area has been popped of the stack. Only the
2665   // return address remains.
2666 
2667   // Pop all the frames we must move/replace.
2668   //
2669   // Frame picture (youngest to oldest)
2670   // 1: self-frame (no frame link)
2671   // 2: deopting frame  (no frame link)
2672   // 3: caller of deopting frame (could be compiled/interpreted).
2673   //
2674   // Note: by leaving the return address of self-frame on the stack
2675   // and using the size of frame 2 to adjust the stack
2676   // when we are done the return to frame 3 will still be on the stack.
2677 
2678   // Pop deoptimized frame
2679   __ addptr(rsp, Address(rdi,Deoptimization::UnrollBlock::size_of_deoptimized_frame_offset_in_bytes()));
2680 
2681   // sp should be pointing at the return address to the caller (3)
2682 
2683   // Pick up the initial fp we should save
2684   // restore rbp before stack bang because if stack overflow is thrown it needs to be pushed (and preserved)
2685   __ movptr(rbp, Address(rdi, Deoptimization::UnrollBlock::initial_info_offset_in_bytes()));
2686 
2687 #ifdef ASSERT
2688   // Compilers generate code that bang the stack by as much as the
2689   // interpreter would need. So this stack banging should never
2690   // trigger a fault. Verify that it does not on non product builds.
2691   if (UseStackBanging) {
2692     __ movl(rbx, Address(rdi ,Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes()));
2693     __ bang_stack_size(rbx, rcx);
2694   }
2695 #endif
2696 
2697   // Load array of frame pcs into ECX
2698   __ movptr(rcx,Address(rdi,Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2699 
2700   __ pop(rsi); // trash the old pc
2701 
2702   // Load array of frame sizes into ESI
2703   __ movptr(rsi,Address(rdi,Deoptimization::UnrollBlock::frame_sizes_offset_in_bytes()));
2704 
2705   Address counter(rdi, Deoptimization::UnrollBlock::counter_temp_offset_in_bytes());
2706 
2707   __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock::number_of_frames_offset_in_bytes()));
2708   __ movl(counter, rbx);
2709 
2710   // Now adjust the caller's stack to make up for the extra locals
2711   // but record the original sp so that we can save it in the skeletal interpreter
2712   // frame and the stack walking of interpreter_sender will get the unextended sp
2713   // value and not the "real" sp value.
2714 
2715   Address sp_temp(rdi, Deoptimization::UnrollBlock::sender_sp_temp_offset_in_bytes());
2716   __ movptr(sp_temp, rsp);
2717   __ movl2ptr(rbx, Address(rdi, Deoptimization::UnrollBlock::caller_adjustment_offset_in_bytes()));
2718   __ subptr(rsp, rbx);
2719 
2720   // Push interpreter frames in a loop
2721   Label loop;
2722   __ bind(loop);
2723   __ movptr(rbx, Address(rsi, 0));      // Load frame size
2724   __ subptr(rbx, 2*wordSize);           // we'll push pc and rbp, by hand
2725   __ pushptr(Address(rcx, 0));          // save return address
2726   __ enter();                           // save old & set new rbp,
2727   __ subptr(rsp, rbx);                  // Prolog!
2728   __ movptr(rbx, sp_temp);              // sender's sp
2729   // This value is corrected by layout_activation_impl
2730   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
2731   __ movptr(Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize), rbx); // Make it walkable
2732   __ movptr(sp_temp, rsp);              // pass to next frame
2733   __ addptr(rsi, wordSize);             // Bump array pointer (sizes)
2734   __ addptr(rcx, wordSize);             // Bump array pointer (pcs)
2735   __ decrementl(counter);             // decrement counter
2736   __ jcc(Assembler::notZero, loop);
2737   __ pushptr(Address(rcx, 0));          // save final return address
2738 
2739   // Re-push self-frame
2740   __ enter();                           // save old & set new rbp,
2741 
2742   //  Return address and rbp, are in place
2743   // We'll push additional args later. Just allocate a full sized
2744   // register save area
2745   __ subptr(rsp, (frame_size_in_words-additional_words - 2) * wordSize);
2746 
2747   // Restore frame locals after moving the frame
2748   __ movptr(Address(rsp, RegisterSaver::raxOffset()*wordSize), rax);
2749   __ movptr(Address(rsp, RegisterSaver::rdxOffset()*wordSize), rdx);
2750   __ fstp_d(Address(rsp, RegisterSaver::fpResultOffset()*wordSize));   // Pop float stack and store in local
2751   if( UseSSE>=2 ) __ movdbl(Address(rsp, RegisterSaver::xmm0Offset()*wordSize), xmm0);
2752   if( UseSSE==1 ) __ movflt(Address(rsp, RegisterSaver::xmm0Offset()*wordSize), xmm0);
2753 
2754   // Set up the args to unpack_frame
2755 
2756   __ pushl(unpack_kind);                     // get the unpack_kind value
2757   __ get_thread(rcx);
2758   __ push(rcx);
2759 
2760   // set last_Java_sp, last_Java_fp
2761   __ set_last_Java_frame(rcx, noreg, rbp, NULL);
2762 
2763   // Call C code.  Need thread but NOT official VM entry
2764   // crud.  We cannot block on this call, no GC can happen.  Call should
2765   // restore return values to their stack-slots with the new SP.
2766   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2767   // Set an oopmap for the call site
2768   oop_maps->add_gc_map( __ pc()-start, new OopMap( frame_size_in_words, 0 ));
2769 
2770   // rax, contains the return result type
2771   __ push(rax);
2772 
2773   __ get_thread(rcx);
2774   __ reset_last_Java_frame(rcx, false);
2775 
2776   // Collect return values
2777   __ movptr(rax,Address(rsp, (RegisterSaver::raxOffset() + additional_words + 1)*wordSize));
2778   __ movptr(rdx,Address(rsp, (RegisterSaver::rdxOffset() + additional_words + 1)*wordSize));
2779 
2780   // Clear floating point stack before returning to interpreter
2781   __ empty_FPU_stack();
2782 
2783   // Check if we should push the float or double return value.
2784   Label results_done, yes_double_value;
2785   __ cmpl(Address(rsp, 0), T_DOUBLE);
2786   __ jcc (Assembler::zero, yes_double_value);
2787   __ cmpl(Address(rsp, 0), T_FLOAT);
2788   __ jcc (Assembler::notZero, results_done);
2789 
2790   // return float value as expected by interpreter
2791   if( UseSSE>=1 ) __ movflt(xmm0, Address(rsp, (RegisterSaver::xmm0Offset() + additional_words + 1)*wordSize));
2792   else            __ fld_d(Address(rsp, (RegisterSaver::fpResultOffset() + additional_words + 1)*wordSize));
2793   __ jmp(results_done);
2794 
2795   // return double value as expected by interpreter
2796   __ bind(yes_double_value);
2797   if( UseSSE>=2 ) __ movdbl(xmm0, Address(rsp, (RegisterSaver::xmm0Offset() + additional_words + 1)*wordSize));
2798   else            __ fld_d(Address(rsp, (RegisterSaver::fpResultOffset() + additional_words + 1)*wordSize));
2799 
2800   __ bind(results_done);
2801 
2802   // Pop self-frame.
2803   __ leave();                              // Epilog!
2804 
2805   // Jump to interpreter
2806   __ ret(0);
2807 
2808   // -------------
2809   // make sure all code is generated
2810   masm->flush();
2811 
2812   _deopt_blob = DeoptimizationBlob::create( &buffer, oop_maps, 0, exception_offset, reexecute_offset, frame_size_in_words);
2813   _deopt_blob->set_unpack_with_exception_in_tls_offset(exception_in_tls_offset);
2814 }
2815 
2816 
2817 #ifdef COMPILER2
2818 //------------------------------generate_uncommon_trap_blob--------------------
2819 void SharedRuntime::generate_uncommon_trap_blob() {
2820   // allocate space for the code
2821   ResourceMark rm;
2822   // setup code generation tools
2823   CodeBuffer   buffer("uncommon_trap_blob", 512, 512);
2824   MacroAssembler* masm = new MacroAssembler(&buffer);
2825 
2826   enum frame_layout {
2827     arg0_off,      // thread                     sp + 0 // Arg location for
2828     arg1_off,      // unloaded_class_index       sp + 1 // calling C
2829     arg2_off,      // exec_mode                  sp + 2
2830     // The frame sender code expects that rbp will be in the "natural" place and
2831     // will override any oopMap setting for it. We must therefore force the layout
2832     // so that it agrees with the frame sender code.
2833     rbp_off,       // callee saved register      sp + 3
2834     return_off,    // slot for return address    sp + 4
2835     framesize
2836   };
2837 
2838   address start = __ pc();
2839 
2840   if (UseRTMLocking) {
2841     // Abort RTM transaction before possible nmethod deoptimization.
2842     __ xabort(0);
2843   }
2844 
2845   // Push self-frame.
2846   __ subptr(rsp, return_off*wordSize);     // Epilog!
2847 
2848   // rbp, is an implicitly saved callee saved register (i.e. the calling
2849   // convention will save restore it in prolog/epilog) Other than that
2850   // there are no callee save registers no that adapter frames are gone.
2851   __ movptr(Address(rsp, rbp_off*wordSize), rbp);
2852 
2853   // Clear the floating point exception stack
2854   __ empty_FPU_stack();
2855 
2856   // set last_Java_sp
2857   __ get_thread(rdx);
2858   __ set_last_Java_frame(rdx, noreg, noreg, NULL);
2859 
2860   // Call C code.  Need thread but NOT official VM entry
2861   // crud.  We cannot block on this call, no GC can happen.  Call should
2862   // capture callee-saved registers as well as return values.
2863   __ movptr(Address(rsp, arg0_off*wordSize), rdx);
2864   // argument already in ECX
2865   __ movl(Address(rsp, arg1_off*wordSize),rcx);
2866   __ movl(Address(rsp, arg2_off*wordSize), Deoptimization::Unpack_uncommon_trap);
2867   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::uncommon_trap)));
2868 
2869   // Set an oopmap for the call site
2870   OopMapSet *oop_maps = new OopMapSet();
2871   OopMap* map =  new OopMap( framesize, 0 );
2872   // No oopMap for rbp, it is known implicitly
2873 
2874   oop_maps->add_gc_map( __ pc()-start, map);
2875 
2876   __ get_thread(rcx);
2877 
2878   __ reset_last_Java_frame(rcx, false);
2879 
2880   // Load UnrollBlock into EDI
2881   __ movptr(rdi, rax);
2882 
2883 #ifdef ASSERT
2884   { Label L;
2885     __ cmpptr(Address(rdi, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes()),
2886             (int32_t)Deoptimization::Unpack_uncommon_trap);
2887     __ jcc(Assembler::equal, L);
2888     __ stop("SharedRuntime::generate_deopt_blob: expected Unpack_uncommon_trap");
2889     __ bind(L);
2890   }
2891 #endif
2892 
2893   // Pop all the frames we must move/replace.
2894   //
2895   // Frame picture (youngest to oldest)
2896   // 1: self-frame (no frame link)
2897   // 2: deopting frame  (no frame link)
2898   // 3: caller of deopting frame (could be compiled/interpreted).
2899 
2900   // Pop self-frame.  We have no frame, and must rely only on EAX and ESP.
2901   __ addptr(rsp,(framesize-1)*wordSize);     // Epilog!
2902 
2903   // Pop deoptimized frame
2904   __ movl2ptr(rcx, Address(rdi,Deoptimization::UnrollBlock::size_of_deoptimized_frame_offset_in_bytes()));
2905   __ addptr(rsp, rcx);
2906 
2907   // sp should be pointing at the return address to the caller (3)
2908 
2909   // Pick up the initial fp we should save
2910   // restore rbp before stack bang because if stack overflow is thrown it needs to be pushed (and preserved)
2911   __ movptr(rbp, Address(rdi, Deoptimization::UnrollBlock::initial_info_offset_in_bytes()));
2912 
2913 #ifdef ASSERT
2914   // Compilers generate code that bang the stack by as much as the
2915   // interpreter would need. So this stack banging should never
2916   // trigger a fault. Verify that it does not on non product builds.
2917   if (UseStackBanging) {
2918     __ movl(rbx, Address(rdi ,Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes()));
2919     __ bang_stack_size(rbx, rcx);
2920   }
2921 #endif
2922 
2923   // Load array of frame pcs into ECX
2924   __ movl(rcx,Address(rdi,Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2925 
2926   __ pop(rsi); // trash the pc
2927 
2928   // Load array of frame sizes into ESI
2929   __ movptr(rsi,Address(rdi,Deoptimization::UnrollBlock::frame_sizes_offset_in_bytes()));
2930 
2931   Address counter(rdi, Deoptimization::UnrollBlock::counter_temp_offset_in_bytes());
2932 
2933   __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock::number_of_frames_offset_in_bytes()));
2934   __ movl(counter, rbx);
2935 
2936   // Now adjust the caller's stack to make up for the extra locals
2937   // but record the original sp so that we can save it in the skeletal interpreter
2938   // frame and the stack walking of interpreter_sender will get the unextended sp
2939   // value and not the "real" sp value.
2940 
2941   Address sp_temp(rdi, Deoptimization::UnrollBlock::sender_sp_temp_offset_in_bytes());
2942   __ movptr(sp_temp, rsp);
2943   __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock::caller_adjustment_offset_in_bytes()));
2944   __ subptr(rsp, rbx);
2945 
2946   // Push interpreter frames in a loop
2947   Label loop;
2948   __ bind(loop);
2949   __ movptr(rbx, Address(rsi, 0));      // Load frame size
2950   __ subptr(rbx, 2*wordSize);           // we'll push pc and rbp, by hand
2951   __ pushptr(Address(rcx, 0));          // save return address
2952   __ enter();                           // save old & set new rbp,
2953   __ subptr(rsp, rbx);                  // Prolog!
2954   __ movptr(rbx, sp_temp);              // sender's sp
2955   // This value is corrected by layout_activation_impl
2956   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD );
2957   __ movptr(Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize), rbx); // Make it walkable
2958   __ movptr(sp_temp, rsp);              // pass to next frame
2959   __ addptr(rsi, wordSize);             // Bump array pointer (sizes)
2960   __ addptr(rcx, wordSize);             // Bump array pointer (pcs)
2961   __ decrementl(counter);             // decrement counter
2962   __ jcc(Assembler::notZero, loop);
2963   __ pushptr(Address(rcx, 0));            // save final return address
2964 
2965   // Re-push self-frame
2966   __ enter();                           // save old & set new rbp,
2967   __ subptr(rsp, (framesize-2) * wordSize);   // Prolog!
2968 
2969 
2970   // set last_Java_sp, last_Java_fp
2971   __ get_thread(rdi);
2972   __ set_last_Java_frame(rdi, noreg, rbp, NULL);
2973 
2974   // Call C code.  Need thread but NOT official VM entry
2975   // crud.  We cannot block on this call, no GC can happen.  Call should
2976   // restore return values to their stack-slots with the new SP.
2977   __ movptr(Address(rsp,arg0_off*wordSize),rdi);
2978   __ movl(Address(rsp,arg1_off*wordSize), Deoptimization::Unpack_uncommon_trap);
2979   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2980   // Set an oopmap for the call site
2981   oop_maps->add_gc_map( __ pc()-start, new OopMap( framesize, 0 ) );
2982 
2983   __ get_thread(rdi);
2984   __ reset_last_Java_frame(rdi, true);
2985 
2986   // Pop self-frame.
2987   __ leave();     // Epilog!
2988 
2989   // Jump to interpreter
2990   __ ret(0);
2991 
2992   // -------------
2993   // make sure all code is generated
2994   masm->flush();
2995 
2996    _uncommon_trap_blob = UncommonTrapBlob::create(&buffer, oop_maps, framesize);
2997 }
2998 #endif // COMPILER2
2999 
3000 //------------------------------generate_handler_blob------
3001 //
3002 // Generate a special Compile2Runtime blob that saves all registers,
3003 // setup oopmap, and calls safepoint code to stop the compiled code for
3004 // a safepoint.
3005 //
3006 SafepointBlob* SharedRuntime::generate_handler_blob(address call_ptr, int poll_type) {
3007 
3008   // Account for thread arg in our frame
3009   const int additional_words = 1;
3010   int frame_size_in_words;
3011 
3012   assert (StubRoutines::forward_exception_entry() != NULL, "must be generated before");
3013 
3014   ResourceMark rm;
3015   OopMapSet *oop_maps = new OopMapSet();
3016   OopMap* map;
3017 
3018   // allocate space for the code
3019   // setup code generation tools
3020   CodeBuffer   buffer("handler_blob", 1024, 512);
3021   MacroAssembler* masm = new MacroAssembler(&buffer);
3022 
3023   const Register java_thread = rdi; // callee-saved for VC++
3024   address start   = __ pc();
3025   address call_pc = NULL;
3026   bool cause_return = (poll_type == POLL_AT_RETURN);
3027   bool save_vectors = (poll_type == POLL_AT_VECTOR_LOOP);
3028 
3029   if (UseRTMLocking) {
3030     // Abort RTM transaction before calling runtime
3031     // because critical section will be large and will be
3032     // aborted anyway. Also nmethod could be deoptimized.
3033     __ xabort(0);
3034   }
3035 
3036   // If cause_return is true we are at a poll_return and there is
3037   // the return address on the stack to the caller on the nmethod
3038   // that is safepoint. We can leave this return on the stack and
3039   // effectively complete the return and safepoint in the caller.
3040   // Otherwise we push space for a return address that the safepoint
3041   // handler will install later to make the stack walking sensible.
3042   if (!cause_return)
3043     __ push(rbx);  // Make room for return address (or push it again)
3044 
3045   map = RegisterSaver::save_live_registers(masm, additional_words, &frame_size_in_words, false, save_vectors);
3046 
3047   // The following is basically a call_VM. However, we need the precise
3048   // address of the call in order to generate an oopmap. Hence, we do all the
3049   // work ourselves.
3050 
3051   // Push thread argument and setup last_Java_sp
3052   __ get_thread(java_thread);
3053   __ push(java_thread);
3054   __ set_last_Java_frame(java_thread, noreg, noreg, NULL);
3055 
3056   // if this was not a poll_return then we need to correct the return address now.
3057   if (!cause_return) {
3058     // Get the return pc saved by the signal handler and stash it in its appropriate place on the stack.
3059     // Additionally, rbx is a callee saved register and we can look at it later to determine
3060     // if someone changed the return address for us!
3061     __ movptr(rbx, Address(java_thread, JavaThread::saved_exception_pc_offset()));
3062     __ movptr(Address(rbp, wordSize), rbx);
3063   }
3064 
3065   // do the call
3066   __ call(RuntimeAddress(call_ptr));
3067 
3068   // Set an oopmap for the call site.  This oopmap will map all
3069   // oop-registers and debug-info registers as callee-saved.  This
3070   // will allow deoptimization at this safepoint to find all possible
3071   // debug-info recordings, as well as let GC find all oops.
3072 
3073   oop_maps->add_gc_map( __ pc() - start, map);
3074 
3075   // Discard arg
3076   __ pop(rcx);
3077 
3078   Label noException;
3079 
3080   // Clear last_Java_sp again
3081   __ get_thread(java_thread);
3082   __ reset_last_Java_frame(java_thread, false);
3083 
3084   __ cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
3085   __ jcc(Assembler::equal, noException);
3086 
3087   // Exception pending
3088   RegisterSaver::restore_live_registers(masm, save_vectors);
3089 
3090   __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3091 
3092   __ bind(noException);
3093 
3094   Label no_adjust, bail, not_special;
3095   if (SafepointMechanism::uses_thread_local_poll() && !cause_return) {
3096     // If our stashed return pc was modified by the runtime we avoid touching it
3097     __ cmpptr(rbx, Address(rbp, wordSize));
3098     __ jccb(Assembler::notEqual, no_adjust);
3099 
3100     // Skip over the poll instruction.
3101     // See NativeInstruction::is_safepoint_poll()
3102     // Possible encodings:
3103     //      85 00       test   %eax,(%rax)
3104     //      85 01       test   %eax,(%rcx)
3105     //      85 02       test   %eax,(%rdx)
3106     //      85 03       test   %eax,(%rbx)
3107     //      85 06       test   %eax,(%rsi)
3108     //      85 07       test   %eax,(%rdi)
3109     //
3110     //      85 04 24    test   %eax,(%rsp)
3111     //      85 45 00    test   %eax,0x0(%rbp)
3112 
3113 #ifdef ASSERT
3114     __ movptr(rax, rbx); // remember where 0x85 should be, for verification below
3115 #endif
3116     // rsp/rbp base encoding takes 3 bytes with the following register values:
3117     // rsp 0x04
3118     // rbp 0x05
3119     __ movzbl(rcx, Address(rbx, 1));
3120     __ andptr(rcx, 0x07); // looking for 0x04 .. 0x05
3121     __ subptr(rcx, 4);    // looking for 0x00 .. 0x01
3122     __ cmpptr(rcx, 1);
3123     __ jcc(Assembler::above, not_special);
3124     __ addptr(rbx, 1);
3125     __ bind(not_special);
3126 #ifdef ASSERT
3127     // Verify the correct encoding of the poll we're about to skip.
3128     __ cmpb(Address(rax, 0), NativeTstRegMem::instruction_code_memXregl);
3129     __ jcc(Assembler::notEqual, bail);
3130     // Mask out the modrm bits
3131     __ testb(Address(rax, 1), NativeTstRegMem::modrm_mask);
3132     // rax encodes to 0, so if the bits are nonzero it's incorrect
3133     __ jcc(Assembler::notZero, bail);
3134 #endif
3135     // Adjust return pc forward to step over the safepoint poll instruction
3136     __ addptr(rbx, 2);
3137     __ movptr(Address(rbp, wordSize), rbx);
3138   }
3139 
3140   __ bind(no_adjust);
3141   // Normal exit, register restoring and exit
3142   RegisterSaver::restore_live_registers(masm, save_vectors);
3143 
3144   __ ret(0);
3145 
3146 #ifdef ASSERT
3147   __ bind(bail);
3148   __ stop("Attempting to adjust pc to skip safepoint poll but the return point is not what we expected");
3149 #endif
3150 
3151   // make sure all code is generated
3152   masm->flush();
3153 
3154   // Fill-out other meta info
3155   return SafepointBlob::create(&buffer, oop_maps, frame_size_in_words);
3156 }
3157 
3158 //
3159 // generate_resolve_blob - call resolution (static/virtual/opt-virtual/ic-miss
3160 //
3161 // Generate a stub that calls into vm to find out the proper destination
3162 // of a java call. All the argument registers are live at this point
3163 // but since this is generic code we don't know what they are and the caller
3164 // must do any gc of the args.
3165 //
3166 RuntimeStub* SharedRuntime::generate_resolve_blob(address destination, const char* name) {
3167   assert (StubRoutines::forward_exception_entry() != NULL, "must be generated before");
3168 
3169   // allocate space for the code
3170   ResourceMark rm;
3171 
3172   CodeBuffer buffer(name, 1000, 512);
3173   MacroAssembler* masm                = new MacroAssembler(&buffer);
3174 
3175   int frame_size_words;
3176   enum frame_layout {
3177                 thread_off,
3178                 extra_words };
3179 
3180   OopMapSet *oop_maps = new OopMapSet();
3181   OopMap* map = NULL;
3182 
3183   int start = __ offset();
3184 
3185   map = RegisterSaver::save_live_registers(masm, extra_words, &frame_size_words);
3186 
3187   int frame_complete = __ offset();
3188 
3189   const Register thread = rdi;
3190   __ get_thread(rdi);
3191 
3192   __ push(thread);
3193   __ set_last_Java_frame(thread, noreg, rbp, NULL);
3194 
3195   __ call(RuntimeAddress(destination));
3196 
3197 
3198   // Set an oopmap for the call site.
3199   // We need this not only for callee-saved registers, but also for volatile
3200   // registers that the compiler might be keeping live across a safepoint.
3201 
3202   oop_maps->add_gc_map( __ offset() - start, map);
3203 
3204   // rax, contains the address we are going to jump to assuming no exception got installed
3205 
3206   __ addptr(rsp, wordSize);
3207 
3208   // clear last_Java_sp
3209   __ reset_last_Java_frame(thread, true);
3210   // check for pending exceptions
3211   Label pending;
3212   __ cmpptr(Address(thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
3213   __ jcc(Assembler::notEqual, pending);
3214 
3215   // get the returned Method*
3216   __ get_vm_result_2(rbx, thread);
3217   __ movptr(Address(rsp, RegisterSaver::rbx_offset() * wordSize), rbx);
3218 
3219   __ movptr(Address(rsp, RegisterSaver::rax_offset() * wordSize), rax);
3220 
3221   RegisterSaver::restore_live_registers(masm);
3222 
3223   // We are back the the original state on entry and ready to go.
3224 
3225   __ jmp(rax);
3226 
3227   // Pending exception after the safepoint
3228 
3229   __ bind(pending);
3230 
3231   RegisterSaver::restore_live_registers(masm);
3232 
3233   // exception pending => remove activation and forward to exception handler
3234 
3235   __ get_thread(thread);
3236   __ movptr(Address(thread, JavaThread::vm_result_offset()), NULL_WORD);
3237   __ movptr(rax, Address(thread, Thread::pending_exception_offset()));
3238   __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3239 
3240   // -------------
3241   // make sure all code is generated
3242   masm->flush();
3243 
3244   // return the  blob
3245   // frame_size_words or bytes??
3246   return RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, frame_size_words, oop_maps, true);
3247 }