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