1 /*
   2  * Copyright (c) 2003, 2015, 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 vect_words = 0;
 118   int num_xmm_regs = XMMRegisterImpl::number_of_registers;
 119 #ifdef COMPILER2
 120   if (save_vectors) {
 121     assert(UseAVX > 0, "512bit vectors are supported only with EVEX");
 122     assert(MaxVectorSize == 64, "only 512bit vectors are supported now");
 123     // Save upper half of ZMM/YMM registers :
 124     vect_words = 8 * 16 / wordSize;
 125     additional_frame_words += vect_words;
 126   }
 127 #else
 128   assert(!save_vectors, "vectors are generated only by C2");
 129 #endif
 130   int frame_size_in_bytes = (reg_save_size + additional_frame_words) * wordSize;
 131   int frame_words = frame_size_in_bytes / wordSize;
 132   *total_frame_words = frame_words;
 133 
 134   assert(FPUStateSizeInWords == 27, "update stack layout");
 135 
 136   // save registers, fpu state, and flags
 137   // We assume caller has already has return address slot on the stack
 138   // We push epb twice in this sequence because we want the real rbp,
 139   // to be under the return like a normal enter and we want to use pusha
 140   // We push by hand instead of pusing push
 141   __ enter();
 142   __ pusha();
 143   __ pushf();
 144   __ subptr(rsp,FPU_regs_live*wordSize); // Push FPU registers space
 145   __ push_FPU_state();          // Save FPU state & init
 146 
 147   if (verify_fpu) {
 148     // Some stubs may have non standard FPU control word settings so
 149     // only check and reset the value when it required to be the
 150     // standard value.  The safepoint blob in particular can be used
 151     // in methods which are using the 24 bit control word for
 152     // optimized float math.
 153 
 154 #ifdef ASSERT
 155     // Make sure the control word has the expected value
 156     Label ok;
 157     __ cmpw(Address(rsp, 0), StubRoutines::fpu_cntrl_wrd_std());
 158     __ jccb(Assembler::equal, ok);
 159     __ stop("corrupted control word detected");
 160     __ bind(ok);
 161 #endif
 162 
 163     // Reset the control word to guard against exceptions being unmasked
 164     // since fstp_d can cause FPU stack underflow exceptions.  Write it
 165     // into the on stack copy and then reload that to make sure that the
 166     // current and future values are correct.
 167     __ movw(Address(rsp, 0), StubRoutines::fpu_cntrl_wrd_std());
 168   }
 169 
 170   __ frstor(Address(rsp, 0));
 171   if (!verify_fpu) {
 172     // Set the control word so that exceptions are masked for the
 173     // following code.
 174     __ fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_std()));
 175   }
 176 
 177   int off = st0_off;
 178   int delta = st1_off - off;
 179 
 180   // Save the FPU registers in de-opt-able form
 181   for (int n = 0; n < FloatRegisterImpl::number_of_registers; n++) {
 182     __ fstp_d(Address(rsp, off*wordSize));
 183     off += delta;
 184   }
 185 
 186   off = xmm0_off;
 187   delta = xmm1_off - off;
 188   if(UseSSE == 1) {           // Save the XMM state
 189     for (int n = 0; n < num_xmm_regs; n++) {
 190       __ movflt(Address(rsp, off*wordSize), as_XMMRegister(n));
 191       off += delta;
 192     }
 193   } else if(UseSSE >= 2) {
 194     // Save whole 128bit (16 bytes) XMM regiters
 195     if (VM_Version::supports_avx512novl()) {
 196       for (int n = 0; n < num_xmm_regs; n++) {
 197         __ vextractf32x4h(Address(rsp, off*wordSize), as_XMMRegister(n), 0);
 198         off += delta;
 199       }
 200     } else {
 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 
 208   if (vect_words > 0) {
 209     assert(vect_words*wordSize == 128, "");
 210     __ subptr(rsp, 128); // Save upper half of YMM registes
 211     off = 0;
 212     for (int n = 0; n < num_xmm_regs; n++) {
 213       __ vextractf128h(Address(rsp, off++*16), as_XMMRegister(n));
 214     }
 215     if (UseAVX > 2) {
 216       __ subptr(rsp, 256); // Save upper half of ZMM registes
 217       off = 0;
 218       for (int n = 0; n < num_xmm_regs; n++) {
 219         __ vextractf64x4h(Address(rsp, off++*32), as_XMMRegister(n));
 220       }
 221     }
 222   }
 223 
 224   // Set an oopmap for the call site.  This oopmap will map all
 225   // oop-registers and debug-info registers as callee-saved.  This
 226   // will allow deoptimization at this safepoint to find all possible
 227   // debug-info recordings, as well as let GC find all oops.
 228 
 229   OopMapSet *oop_maps = new OopMapSet();
 230   OopMap* map =  new OopMap( frame_words, 0 );
 231 
 232 #define STACK_OFFSET(x) VMRegImpl::stack2reg((x) + additional_frame_words)
 233 #define NEXTREG(x) (x)->as_VMReg()->next()
 234 
 235   map->set_callee_saved(STACK_OFFSET(rax_off), rax->as_VMReg());
 236   map->set_callee_saved(STACK_OFFSET(rcx_off), rcx->as_VMReg());
 237   map->set_callee_saved(STACK_OFFSET(rdx_off), rdx->as_VMReg());
 238   map->set_callee_saved(STACK_OFFSET(rbx_off), rbx->as_VMReg());
 239   // rbp, location is known implicitly, no oopMap
 240   map->set_callee_saved(STACK_OFFSET(rsi_off), rsi->as_VMReg());
 241   map->set_callee_saved(STACK_OFFSET(rdi_off), rdi->as_VMReg());
 242   // %%% This is really a waste but we'll keep things as they were for now for the upper component
 243   off = st0_off;
 244   delta = st1_off - off;
 245   for (int n = 0; n < FloatRegisterImpl::number_of_registers; n++) {
 246     FloatRegister freg_name = as_FloatRegister(n);
 247     map->set_callee_saved(STACK_OFFSET(off), freg_name->as_VMReg());
 248     map->set_callee_saved(STACK_OFFSET(off+1), NEXTREG(freg_name));
 249     off += delta;
 250   }
 251   off = xmm0_off;
 252   delta = xmm1_off - off;
 253   for (int n = 0; n < num_xmm_regs; n++) {
 254     XMMRegister xmm_name = as_XMMRegister(n);
 255     map->set_callee_saved(STACK_OFFSET(off), xmm_name->as_VMReg());
 256     map->set_callee_saved(STACK_OFFSET(off+1), NEXTREG(xmm_name));
 257     off += delta;
 258   }
 259 #undef NEXTREG
 260 #undef STACK_OFFSET
 261 
 262   return map;
 263 }
 264 
 265 void RegisterSaver::restore_live_registers(MacroAssembler* masm, bool restore_vectors) {
 266   int num_xmm_regs = XMMRegisterImpl::number_of_registers;
 267   // Recover XMM & FPU state
 268   int additional_frame_bytes = 0;
 269 #ifdef COMPILER2
 270   if (restore_vectors) {
 271     assert(UseAVX > 0, "512bit vectors are supported only with EVEX");
 272     assert(MaxVectorSize == 64, "only 512bit vectors are supported now");
 273     additional_frame_bytes = 128;
 274   }
 275 #else
 276   assert(!restore_vectors, "vectors are generated only by C2");
 277 #endif
 278   int off = xmm0_off;
 279   int delta = xmm1_off - off;
 280 
 281   if (UseSSE == 1) {
 282     assert(additional_frame_bytes == 0, "");
 283     for (int n = 0; n < num_xmm_regs; n++) {
 284       __ movflt(as_XMMRegister(n), Address(rsp, off*wordSize));
 285       off += delta;
 286     }
 287   } else if (UseSSE >= 2) {
 288     if (VM_Version::supports_avx512novl()) {
 289       for (int n = 0; n < num_xmm_regs; n++) {
 290         __ vinsertf32x4h(as_XMMRegister(n), Address(rsp, off*wordSize+additional_frame_bytes), 0);
 291         off += delta;
 292       }
 293     } else {
 294       for (int n = 0; n < num_xmm_regs; n++) {
 295         __ movdqu(as_XMMRegister(n), Address(rsp, off*wordSize+additional_frame_bytes));
 296         off += delta;
 297       }
 298     }
 299   }
 300   if (restore_vectors) {
 301     if (UseAVX > 2) {
 302       off = 0;
 303       for (int n = 0; n < num_xmm_regs; n++) {
 304         __ vinsertf64x4h(as_XMMRegister(n), Address(rsp, off++*32));
 305       }
 306       __ addptr(rsp, additional_frame_bytes*2); // Save upper half of ZMM registes
 307     }
 308     // Restore upper half of YMM registes.
 309     assert(additional_frame_bytes == 128, "");
 310     off = 0;
 311     for (int n = 0; n < num_xmm_regs; n++) {
 312       __ vinsertf128h(as_XMMRegister(n), Address(rsp, off++*16));
 313     }
 314     __ addptr(rsp, additional_frame_bytes); // Save upper half of YMM registes
 315   }
 316   __ pop_FPU_state();
 317   __ addptr(rsp, FPU_regs_live*wordSize); // Pop FPU registers
 318 
 319   __ popf();
 320   __ popa();
 321   // Get the rbp, described implicitly by the frame sender code (no oopMap)
 322   __ pop(rbp);
 323 
 324 }
 325 
 326 void RegisterSaver::restore_result_registers(MacroAssembler* masm) {
 327 
 328   // Just restore result register. Only used by deoptimization. By
 329   // now any callee save register that needs to be restore to a c2
 330   // caller of the deoptee has been extracted into the vframeArray
 331   // and will be stuffed into the c2i adapter we create for later
 332   // restoration so only result registers need to be restored here.
 333   //
 334 
 335   __ frstor(Address(rsp, 0));      // Restore fpu state
 336 
 337   // Recover XMM & FPU state
 338   if( UseSSE == 1 ) {
 339     __ movflt(xmm0, Address(rsp, xmm0_off*wordSize));
 340   } else if( UseSSE >= 2 ) {
 341     __ movdbl(xmm0, Address(rsp, xmm0_off*wordSize));
 342   }
 343   __ movptr(rax, Address(rsp, rax_off*wordSize));
 344   __ movptr(rdx, Address(rsp, rdx_off*wordSize));
 345   // Pop all of the register save are off the stack except the return address
 346   __ addptr(rsp, return_off * wordSize);
 347 }
 348 
 349 // Is vector's size (in bytes) bigger than a size saved by default?
 350 // 16 bytes XMM registers are saved by default using SSE2 movdqu instructions.
 351 // Note, MaxVectorSize == 0 with UseSSE < 2 and vectors are not generated.
 352 bool SharedRuntime::is_wide_vector(int size) {
 353   return size > 16;
 354 }
 355 
 356 // The java_calling_convention describes stack locations as ideal slots on
 357 // a frame with no abi restrictions. Since we must observe abi restrictions
 358 // (like the placement of the register window) the slots must be biased by
 359 // the following value.
 360 static int reg2offset_in(VMReg r) {
 361   // Account for saved rbp, and return address
 362   // This should really be in_preserve_stack_slots
 363   return (r->reg2stack() + 2) * VMRegImpl::stack_slot_size;
 364 }
 365 
 366 static int reg2offset_out(VMReg r) {
 367   return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
 368 }
 369 
 370 // ---------------------------------------------------------------------------
 371 // Read the array of BasicTypes from a signature, and compute where the
 372 // arguments should go.  Values in the VMRegPair regs array refer to 4-byte
 373 // quantities.  Values less than SharedInfo::stack0 are registers, those above
 374 // refer to 4-byte stack slots.  All stack slots are based off of the stack pointer
 375 // as framesizes are fixed.
 376 // VMRegImpl::stack0 refers to the first slot 0(sp).
 377 // and VMRegImpl::stack0+1 refers to the memory word 4-byes higher.  Register
 378 // up to RegisterImpl::number_of_registers) are the 32-bit
 379 // integer registers.
 380 
 381 // Pass first two oop/int args in registers ECX and EDX.
 382 // Pass first two float/double args in registers XMM0 and XMM1.
 383 // Doubles have precedence, so if you pass a mix of floats and doubles
 384 // the doubles will grab the registers before the floats will.
 385 
 386 // Note: the INPUTS in sig_bt are in units of Java argument words, which are
 387 // either 32-bit or 64-bit depending on the build.  The OUTPUTS are in 32-bit
 388 // units regardless of build. Of course for i486 there is no 64 bit build
 389 
 390 
 391 // ---------------------------------------------------------------------------
 392 // The compiled Java calling convention.
 393 // Pass first two oop/int args in registers ECX and EDX.
 394 // Pass first two float/double args in registers XMM0 and XMM1.
 395 // Doubles have precedence, so if you pass a mix of floats and doubles
 396 // the doubles will grab the registers before the floats will.
 397 int SharedRuntime::java_calling_convention(const BasicType *sig_bt,
 398                                            VMRegPair *regs,
 399                                            int total_args_passed,
 400                                            int is_outgoing) {
 401   uint    stack = 0;          // Starting stack position for args on stack
 402 
 403 
 404   // Pass first two oop/int args in registers ECX and EDX.
 405   uint reg_arg0 = 9999;
 406   uint reg_arg1 = 9999;
 407 
 408   // Pass first two float/double args in registers XMM0 and XMM1.
 409   // Doubles have precedence, so if you pass a mix of floats and doubles
 410   // the doubles will grab the registers before the floats will.
 411   // CNC - TURNED OFF FOR non-SSE.
 412   //       On Intel we have to round all doubles (and most floats) at
 413   //       call sites by storing to the stack in any case.
 414   // UseSSE=0 ==> Don't Use ==> 9999+0
 415   // UseSSE=1 ==> Floats only ==> 9999+1
 416   // UseSSE>=2 ==> Floats or doubles ==> 9999+2
 417   enum { fltarg_dontuse = 9999+0, fltarg_float_only = 9999+1, fltarg_flt_dbl = 9999+2 };
 418   uint fargs = (UseSSE>=2) ? 2 : UseSSE;
 419   uint freg_arg0 = 9999+fargs;
 420   uint freg_arg1 = 9999+fargs;
 421 
 422   // Pass doubles & longs aligned on the stack.  First count stack slots for doubles
 423   int i;
 424   for( i = 0; i < total_args_passed; i++) {
 425     if( sig_bt[i] == T_DOUBLE ) {
 426       // first 2 doubles go in registers
 427       if( freg_arg0 == fltarg_flt_dbl ) freg_arg0 = i;
 428       else if( freg_arg1 == fltarg_flt_dbl ) freg_arg1 = i;
 429       else // Else double is passed low on the stack to be aligned.
 430         stack += 2;
 431     } else if( sig_bt[i] == T_LONG ) {
 432       stack += 2;
 433     }
 434   }
 435   int dstack = 0;             // Separate counter for placing doubles
 436 
 437   // Now pick where all else goes.
 438   for( i = 0; i < total_args_passed; i++) {
 439     // From the type and the argument number (count) compute the location
 440     switch( sig_bt[i] ) {
 441     case T_SHORT:
 442     case T_CHAR:
 443     case T_BYTE:
 444     case T_BOOLEAN:
 445     case T_INT:
 446     case T_ARRAY:
 447     case T_OBJECT:
 448     case T_ADDRESS:
 449       if( reg_arg0 == 9999 )  {
 450         reg_arg0 = i;
 451         regs[i].set1(rcx->as_VMReg());
 452       } else if( reg_arg1 == 9999 )  {
 453         reg_arg1 = i;
 454         regs[i].set1(rdx->as_VMReg());
 455       } else {
 456         regs[i].set1(VMRegImpl::stack2reg(stack++));
 457       }
 458       break;
 459     case T_FLOAT:
 460       if( freg_arg0 == fltarg_flt_dbl || freg_arg0 == fltarg_float_only ) {
 461         freg_arg0 = i;
 462         regs[i].set1(xmm0->as_VMReg());
 463       } else if( freg_arg1 == fltarg_flt_dbl || freg_arg1 == fltarg_float_only ) {
 464         freg_arg1 = i;
 465         regs[i].set1(xmm1->as_VMReg());
 466       } else {
 467         regs[i].set1(VMRegImpl::stack2reg(stack++));
 468       }
 469       break;
 470     case T_LONG:
 471       assert(sig_bt[i+1] == T_VOID, "missing Half" );
 472       regs[i].set2(VMRegImpl::stack2reg(dstack));
 473       dstack += 2;
 474       break;
 475     case T_DOUBLE:
 476       assert(sig_bt[i+1] == T_VOID, "missing Half" );
 477       if( freg_arg0 == (uint)i ) {
 478         regs[i].set2(xmm0->as_VMReg());
 479       } else if( freg_arg1 == (uint)i ) {
 480         regs[i].set2(xmm1->as_VMReg());
 481       } else {
 482         regs[i].set2(VMRegImpl::stack2reg(dstack));
 483         dstack += 2;
 484       }
 485       break;
 486     case T_VOID: regs[i].set_bad(); break;
 487       break;
 488     default:
 489       ShouldNotReachHere();
 490       break;
 491     }
 492   }
 493 
 494   // return value can be odd number of VMRegImpl stack slots make multiple of 2
 495   return round_to(stack, 2);
 496 }
 497 
 498 // Patch the callers callsite with entry to compiled code if it exists.
 499 static void patch_callers_callsite(MacroAssembler *masm) {
 500   Label L;
 501   __ cmpptr(Address(rbx, in_bytes(Method::code_offset())), (int32_t)NULL_WORD);
 502   __ jcc(Assembler::equal, L);
 503   // Schedule the branch target address early.
 504   // Call into the VM to patch the caller, then jump to compiled callee
 505   // rax, isn't live so capture return address while we easily can
 506   __ movptr(rax, Address(rsp, 0));
 507   __ pusha();
 508   __ pushf();
 509 
 510   if (UseSSE == 1) {
 511     __ subptr(rsp, 2*wordSize);
 512     __ movflt(Address(rsp, 0), xmm0);
 513     __ movflt(Address(rsp, wordSize), xmm1);
 514   }
 515   if (UseSSE >= 2) {
 516     __ subptr(rsp, 4*wordSize);
 517     __ movdbl(Address(rsp, 0), xmm0);
 518     __ movdbl(Address(rsp, 2*wordSize), xmm1);
 519   }
 520 #ifdef COMPILER2
 521   // C2 may leave the stack dirty if not in SSE2+ mode
 522   if (UseSSE >= 2) {
 523     __ verify_FPU(0, "c2i transition should have clean FPU stack");
 524   } else {
 525     __ empty_FPU_stack();
 526   }
 527 #endif /* COMPILER2 */
 528 
 529   // VM needs caller's callsite
 530   __ push(rax);
 531   // VM needs target method
 532   __ push(rbx);
 533   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::fixup_callers_callsite)));
 534   __ addptr(rsp, 2*wordSize);
 535 
 536   if (UseSSE == 1) {
 537     __ movflt(xmm0, Address(rsp, 0));
 538     __ movflt(xmm1, Address(rsp, wordSize));
 539     __ addptr(rsp, 2*wordSize);
 540   }
 541   if (UseSSE >= 2) {
 542     __ movdbl(xmm0, Address(rsp, 0));
 543     __ movdbl(xmm1, Address(rsp, 2*wordSize));
 544     __ addptr(rsp, 4*wordSize);
 545   }
 546 
 547   __ popf();
 548   __ popa();
 549   __ bind(L);
 550 }
 551 
 552 
 553 static void move_c2i_double(MacroAssembler *masm, XMMRegister r, int st_off) {
 554   int next_off = st_off - Interpreter::stackElementSize;
 555   __ movdbl(Address(rsp, next_off), r);
 556 }
 557 
 558 static void gen_c2i_adapter(MacroAssembler *masm,
 559                             int total_args_passed,
 560                             int comp_args_on_stack,
 561                             const BasicType *sig_bt,
 562                             const VMRegPair *regs,
 563                             Label& skip_fixup) {
 564   // Before we get into the guts of the C2I adapter, see if we should be here
 565   // at all.  We've come from compiled code and are attempting to jump to the
 566   // interpreter, which means the caller made a static call to get here
 567   // (vcalls always get a compiled target if there is one).  Check for a
 568   // compiled target.  If there is one, we need to patch the caller's call.
 569   patch_callers_callsite(masm);
 570 
 571   __ bind(skip_fixup);
 572 
 573 #ifdef COMPILER2
 574   // C2 may leave the stack dirty if not in SSE2+ mode
 575   if (UseSSE >= 2) {
 576     __ verify_FPU(0, "c2i transition should have clean FPU stack");
 577   } else {
 578     __ empty_FPU_stack();
 579   }
 580 #endif /* COMPILER2 */
 581 
 582   // Since all args are passed on the stack, total_args_passed * interpreter_
 583   // stack_element_size  is the
 584   // space we need.
 585   int extraspace = total_args_passed * Interpreter::stackElementSize;
 586 
 587   // Get return address
 588   __ pop(rax);
 589 
 590   // set senderSP value
 591   __ movptr(rsi, rsp);
 592 
 593   __ subptr(rsp, extraspace);
 594 
 595   // Now write the args into the outgoing interpreter space
 596   for (int i = 0; i < total_args_passed; i++) {
 597     if (sig_bt[i] == T_VOID) {
 598       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
 599       continue;
 600     }
 601 
 602     // st_off points to lowest address on stack.
 603     int st_off = ((total_args_passed - 1) - i) * Interpreter::stackElementSize;
 604     int next_off = st_off - Interpreter::stackElementSize;
 605 
 606     // Say 4 args:
 607     // i   st_off
 608     // 0   12 T_LONG
 609     // 1    8 T_VOID
 610     // 2    4 T_OBJECT
 611     // 3    0 T_BOOL
 612     VMReg r_1 = regs[i].first();
 613     VMReg r_2 = regs[i].second();
 614     if (!r_1->is_valid()) {
 615       assert(!r_2->is_valid(), "");
 616       continue;
 617     }
 618 
 619     if (r_1->is_stack()) {
 620       // memory to memory use fpu stack top
 621       int ld_off = r_1->reg2stack() * VMRegImpl::stack_slot_size + extraspace;
 622 
 623       if (!r_2->is_valid()) {
 624         __ movl(rdi, Address(rsp, ld_off));
 625         __ movptr(Address(rsp, st_off), rdi);
 626       } else {
 627 
 628         // ld_off == LSW, ld_off+VMRegImpl::stack_slot_size == MSW
 629         // st_off == MSW, st_off-wordSize == LSW
 630 
 631         __ movptr(rdi, Address(rsp, ld_off));
 632         __ movptr(Address(rsp, next_off), rdi);
 633 #ifndef _LP64
 634         __ movptr(rdi, Address(rsp, ld_off + wordSize));
 635         __ movptr(Address(rsp, st_off), rdi);
 636 #else
 637 #ifdef ASSERT
 638         // Overwrite the unused slot with known junk
 639         __ mov64(rax, CONST64(0xdeadffffdeadaaaa));
 640         __ movptr(Address(rsp, st_off), rax);
 641 #endif /* ASSERT */
 642 #endif // _LP64
 643       }
 644     } else if (r_1->is_Register()) {
 645       Register r = r_1->as_Register();
 646       if (!r_2->is_valid()) {
 647         __ movl(Address(rsp, st_off), r);
 648       } else {
 649         // long/double in gpr
 650         NOT_LP64(ShouldNotReachHere());
 651         // Two VMRegs can be T_OBJECT, T_ADDRESS, T_DOUBLE, T_LONG
 652         // T_DOUBLE and T_LONG use two slots in the interpreter
 653         if ( sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
 654           // long/double in gpr
 655 #ifdef ASSERT
 656           // Overwrite the unused slot with known junk
 657           LP64_ONLY(__ mov64(rax, CONST64(0xdeadffffdeadaaab)));
 658           __ movptr(Address(rsp, st_off), rax);
 659 #endif /* ASSERT */
 660           __ movptr(Address(rsp, next_off), r);
 661         } else {
 662           __ movptr(Address(rsp, st_off), r);
 663         }
 664       }
 665     } else {
 666       assert(r_1->is_XMMRegister(), "");
 667       if (!r_2->is_valid()) {
 668         __ movflt(Address(rsp, st_off), r_1->as_XMMRegister());
 669       } else {
 670         assert(sig_bt[i] == T_DOUBLE || sig_bt[i] == T_LONG, "wrong type");
 671         move_c2i_double(masm, r_1->as_XMMRegister(), st_off);
 672       }
 673     }
 674   }
 675 
 676   // Schedule the branch target address early.
 677   __ movptr(rcx, Address(rbx, in_bytes(Method::interpreter_entry_offset())));
 678   // And repush original return address
 679   __ push(rax);
 680   __ jmp(rcx);
 681 }
 682 
 683 
 684 static void move_i2c_double(MacroAssembler *masm, XMMRegister r, Register saved_sp, int ld_off) {
 685   int next_val_off = ld_off - Interpreter::stackElementSize;
 686   __ movdbl(r, Address(saved_sp, next_val_off));
 687 }
 688 
 689 static void range_check(MacroAssembler* masm, Register pc_reg, Register temp_reg,
 690                         address code_start, address code_end,
 691                         Label& L_ok) {
 692   Label L_fail;
 693   __ lea(temp_reg, ExternalAddress(code_start));
 694   __ cmpptr(pc_reg, temp_reg);
 695   __ jcc(Assembler::belowEqual, L_fail);
 696   __ lea(temp_reg, ExternalAddress(code_end));
 697   __ cmpptr(pc_reg, temp_reg);
 698   __ jcc(Assembler::below, L_ok);
 699   __ bind(L_fail);
 700 }
 701 
 702 static void gen_i2c_adapter(MacroAssembler *masm,
 703                             int total_args_passed,
 704                             int comp_args_on_stack,
 705                             const BasicType *sig_bt,
 706                             const VMRegPair *regs) {
 707 
 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 GC_locker::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 GC_locker::needs_gc");
1303   Label cont;
1304   __ cmp8(ExternalAddress((address)GC_locker::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(err_msg_res("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 GC_locker
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 (GC_locker::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                                                 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   if (InlineObjectHash && method->intrinsic_id() == vmIntrinsics::_hashCode) {
1758     // Object.hashCode can pull the hashCode from the header word
1759     // instead of doing a full VM transition once it's been computed.
1760     // Since hashCode is usually polymorphic at call sites we can't do
1761     // this optimization at the call site without a lot of work.
1762     Label slowCase;
1763     Register receiver = rcx;
1764     Register result = rax;
1765     __ movptr(result, Address(receiver, oopDesc::mark_offset_in_bytes()));
1766 
1767     // check if locked
1768     __ testptr(result, markOopDesc::unlocked_value);
1769     __ jcc (Assembler::zero, slowCase);
1770 
1771     if (UseBiasedLocking) {
1772       // Check if biased and fall through to runtime if so
1773       __ testptr(result, markOopDesc::biased_lock_bit_in_place);
1774       __ jcc (Assembler::notZero, slowCase);
1775     }
1776 
1777     // get hash
1778     __ andptr(result, markOopDesc::hash_mask_in_place);
1779     // test if hashCode exists
1780     __ jcc  (Assembler::zero, slowCase);
1781     __ shrptr(result, markOopDesc::hash_shift);
1782     __ ret(0);
1783     __ bind (slowCase);
1784   }
1785 #endif // COMPILER1
1786 
1787   // The instruction at the verified entry point must be 5 bytes or longer
1788   // because it can be patched on the fly by make_non_entrant. The stack bang
1789   // instruction fits that requirement.
1790 
1791   // Generate stack overflow check
1792 
1793   if (UseStackBanging) {
1794     __ bang_stack_with_offset(StackShadowPages*os::vm_page_size());
1795   } else {
1796     // need a 5 byte instruction to allow MT safe patching to non-entrant
1797     __ fat_nop();
1798   }
1799 
1800   // Generate a new frame for the wrapper.
1801   __ enter();
1802   // -2 because return address is already present and so is saved rbp
1803   __ subptr(rsp, stack_size - 2*wordSize);
1804 
1805   // Frame is now completed as far as size and linkage.
1806   int frame_complete = ((intptr_t)__ pc()) - start;
1807 
1808   if (UseRTMLocking) {
1809     // Abort RTM transaction before calling JNI
1810     // because critical section will be large and will be
1811     // aborted anyway. Also nmethod could be deoptimized.
1812     __ xabort(0);
1813   }
1814 
1815   // Calculate the difference between rsp and rbp,. We need to know it
1816   // after the native call because on windows Java Natives will pop
1817   // the arguments and it is painful to do rsp relative addressing
1818   // in a platform independent way. So after the call we switch to
1819   // rbp, relative addressing.
1820 
1821   int fp_adjustment = stack_size - 2*wordSize;
1822 
1823 #ifdef COMPILER2
1824   // C2 may leave the stack dirty if not in SSE2+ mode
1825   if (UseSSE >= 2) {
1826     __ verify_FPU(0, "c2i transition should have clean FPU stack");
1827   } else {
1828     __ empty_FPU_stack();
1829   }
1830 #endif /* COMPILER2 */
1831 
1832   // Compute the rbp, offset for any slots used after the jni call
1833 
1834   int lock_slot_rbp_offset = (lock_slot_offset*VMRegImpl::stack_slot_size) - fp_adjustment;
1835 
1836   // We use rdi as a thread pointer because it is callee save and
1837   // if we load it once it is usable thru the entire wrapper
1838   const Register thread = rdi;
1839 
1840   // We use rsi as the oop handle for the receiver/klass
1841   // It is callee save so it survives the call to native
1842 
1843   const Register oop_handle_reg = rsi;
1844 
1845   __ get_thread(thread);
1846 
1847   if (is_critical_native) {
1848     check_needs_gc_for_critical_native(masm, thread, stack_slots, total_c_args, total_in_args,
1849                                        oop_handle_offset, oop_maps, in_regs, in_sig_bt);
1850   }
1851 
1852   //
1853   // We immediately shuffle the arguments so that any vm call we have to
1854   // make from here on out (sync slow path, jvmti, etc.) we will have
1855   // captured the oops from our caller and have a valid oopMap for
1856   // them.
1857 
1858   // -----------------
1859   // The Grand Shuffle
1860   //
1861   // Natives require 1 or 2 extra arguments over the normal ones: the JNIEnv*
1862   // and, if static, the class mirror instead of a receiver.  This pretty much
1863   // guarantees that register layout will not match (and x86 doesn't use reg
1864   // parms though amd does).  Since the native abi doesn't use register args
1865   // and the java conventions does we don't have to worry about collisions.
1866   // All of our moved are reg->stack or stack->stack.
1867   // We ignore the extra arguments during the shuffle and handle them at the
1868   // last moment. The shuffle is described by the two calling convention
1869   // vectors we have in our possession. We simply walk the java vector to
1870   // get the source locations and the c vector to get the destinations.
1871 
1872   int c_arg = is_critical_native ? 0 : (method->is_static() ? 2 : 1 );
1873 
1874   // Record rsp-based slot for receiver on stack for non-static methods
1875   int receiver_offset = -1;
1876 
1877   // This is a trick. We double the stack slots so we can claim
1878   // the oops in the caller's frame. Since we are sure to have
1879   // more args than the caller doubling is enough to make
1880   // sure we can capture all the incoming oop args from the
1881   // caller.
1882   //
1883   OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1884 
1885   // Mark location of rbp,
1886   // map->set_callee_saved(VMRegImpl::stack2reg( stack_slots - 2), stack_slots * 2, 0, rbp->as_VMReg());
1887 
1888   // We know that we only have args in at most two integer registers (rcx, rdx). So rax, rbx
1889   // Are free to temporaries if we have to do  stack to steck moves.
1890   // All inbound args are referenced based on rbp, and all outbound args via rsp.
1891 
1892   for (int i = 0; i < total_in_args ; i++, c_arg++ ) {
1893     switch (in_sig_bt[i]) {
1894       case T_ARRAY:
1895         if (is_critical_native) {
1896           unpack_array_argument(masm, in_regs[i], in_elem_bt[i], out_regs[c_arg + 1], out_regs[c_arg]);
1897           c_arg++;
1898           break;
1899         }
1900       case T_OBJECT:
1901         assert(!is_critical_native, "no oop arguments");
1902         object_move(masm, map, oop_handle_offset, stack_slots, in_regs[i], out_regs[c_arg],
1903                     ((i == 0) && (!is_static)),
1904                     &receiver_offset);
1905         break;
1906       case T_VOID:
1907         break;
1908 
1909       case T_FLOAT:
1910         float_move(masm, in_regs[i], out_regs[c_arg]);
1911           break;
1912 
1913       case T_DOUBLE:
1914         assert( i + 1 < total_in_args &&
1915                 in_sig_bt[i + 1] == T_VOID &&
1916                 out_sig_bt[c_arg+1] == T_VOID, "bad arg list");
1917         double_move(masm, in_regs[i], out_regs[c_arg]);
1918         break;
1919 
1920       case T_LONG :
1921         long_move(masm, in_regs[i], out_regs[c_arg]);
1922         break;
1923 
1924       case T_ADDRESS: assert(false, "found T_ADDRESS in java args");
1925 
1926       default:
1927         simple_move32(masm, in_regs[i], out_regs[c_arg]);
1928     }
1929   }
1930 
1931   // Pre-load a static method's oop into rsi.  Used both by locking code and
1932   // the normal JNI call code.
1933   if (method->is_static() && !is_critical_native) {
1934 
1935     //  load opp into a register
1936     __ movoop(oop_handle_reg, JNIHandles::make_local(method->method_holder()->java_mirror()));
1937 
1938     // Now handlize the static class mirror it's known not-null.
1939     __ movptr(Address(rsp, klass_offset), oop_handle_reg);
1940     map->set_oop(VMRegImpl::stack2reg(klass_slot_offset));
1941 
1942     // Now get the handle
1943     __ lea(oop_handle_reg, Address(rsp, klass_offset));
1944     // store the klass handle as second argument
1945     __ movptr(Address(rsp, wordSize), oop_handle_reg);
1946   }
1947 
1948   // Change state to native (we save the return address in the thread, since it might not
1949   // be pushed on the stack when we do a a stack traversal). It is enough that the pc()
1950   // points into the right code segment. It does not have to be the correct return pc.
1951   // We use the same pc/oopMap repeatedly when we call out
1952 
1953   intptr_t the_pc = (intptr_t) __ pc();
1954   oop_maps->add_gc_map(the_pc - start, map);
1955 
1956   __ set_last_Java_frame(thread, rsp, noreg, (address)the_pc);
1957 
1958 
1959   // We have all of the arguments setup at this point. We must not touch any register
1960   // argument registers at this point (what if we save/restore them there are no oop?
1961 
1962   {
1963     SkipIfEqual skip_if(masm, &DTraceMethodProbes, 0);
1964     __ mov_metadata(rax, method());
1965     __ call_VM_leaf(
1966          CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry),
1967          thread, rax);
1968   }
1969 
1970   // RedefineClasses() tracing support for obsolete method entry
1971   if (RC_TRACE_IN_RANGE(0x00001000, 0x00002000)) {
1972     __ mov_metadata(rax, method());
1973     __ call_VM_leaf(
1974          CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
1975          thread, rax);
1976   }
1977 
1978   // These are register definitions we need for locking/unlocking
1979   const Register swap_reg = rax;  // Must use rax, for cmpxchg instruction
1980   const Register obj_reg  = rcx;  // Will contain the oop
1981   const Register lock_reg = rdx;  // Address of compiler lock object (BasicLock)
1982 
1983   Label slow_path_lock;
1984   Label lock_done;
1985 
1986   // Lock a synchronized method
1987   if (method->is_synchronized()) {
1988     assert(!is_critical_native, "unhandled");
1989 
1990 
1991     const int mark_word_offset = BasicLock::displaced_header_offset_in_bytes();
1992 
1993     // Get the handle (the 2nd argument)
1994     __ movptr(oop_handle_reg, Address(rsp, wordSize));
1995 
1996     // Get address of the box
1997 
1998     __ lea(lock_reg, Address(rbp, lock_slot_rbp_offset));
1999 
2000     // Load the oop from the handle
2001     __ movptr(obj_reg, Address(oop_handle_reg, 0));
2002 
2003     if (UseBiasedLocking) {
2004       // Note that oop_handle_reg is trashed during this call
2005       __ biased_locking_enter(lock_reg, obj_reg, swap_reg, oop_handle_reg, false, lock_done, &slow_path_lock);
2006     }
2007 
2008     // Load immediate 1 into swap_reg %rax,
2009     __ movptr(swap_reg, 1);
2010 
2011     // Load (object->mark() | 1) into swap_reg %rax,
2012     __ orptr(swap_reg, Address(obj_reg, 0));
2013 
2014     // Save (object->mark() | 1) into BasicLock's displaced header
2015     __ movptr(Address(lock_reg, mark_word_offset), swap_reg);
2016 
2017     if (os::is_MP()) {
2018       __ lock();
2019     }
2020 
2021     // src -> dest iff dest == rax, else rax, <- dest
2022     // *obj_reg = lock_reg iff *obj_reg == rax, else rax, = *(obj_reg)
2023     __ cmpxchgptr(lock_reg, Address(obj_reg, 0));
2024     __ jcc(Assembler::equal, lock_done);
2025 
2026     // Test if the oopMark is an obvious stack pointer, i.e.,
2027     //  1) (mark & 3) == 0, and
2028     //  2) rsp <= mark < mark + os::pagesize()
2029     // These 3 tests can be done by evaluating the following
2030     // expression: ((mark - rsp) & (3 - os::vm_page_size())),
2031     // assuming both stack pointer and pagesize have their
2032     // least significant 2 bits clear.
2033     // NOTE: the oopMark is in swap_reg %rax, as the result of cmpxchg
2034 
2035     __ subptr(swap_reg, rsp);
2036     __ andptr(swap_reg, 3 - os::vm_page_size());
2037 
2038     // Save the test result, for recursive case, the result is zero
2039     __ movptr(Address(lock_reg, mark_word_offset), swap_reg);
2040     __ jcc(Assembler::notEqual, slow_path_lock);
2041     // Slow path will re-enter here
2042     __ bind(lock_done);
2043 
2044     if (UseBiasedLocking) {
2045       // Re-fetch oop_handle_reg as we trashed it above
2046       __ movptr(oop_handle_reg, Address(rsp, wordSize));
2047     }
2048   }
2049 
2050 
2051   // Finally just about ready to make the JNI call
2052 
2053 
2054   // get JNIEnv* which is first argument to native
2055   if (!is_critical_native) {
2056     __ lea(rdx, Address(thread, in_bytes(JavaThread::jni_environment_offset())));
2057     __ movptr(Address(rsp, 0), rdx);
2058   }
2059 
2060   // Now set thread in native
2061   __ movl(Address(thread, JavaThread::thread_state_offset()), _thread_in_native);
2062 
2063   __ call(RuntimeAddress(native_func));
2064 
2065   // Verify or restore cpu control state after JNI call
2066   __ restore_cpu_control_state_after_jni();
2067 
2068   // WARNING - on Windows Java Natives use pascal calling convention and pop the
2069   // arguments off of the stack. We could just re-adjust the stack pointer here
2070   // and continue to do SP relative addressing but we instead switch to FP
2071   // relative addressing.
2072 
2073   // Unpack native results.
2074   switch (ret_type) {
2075   case T_BOOLEAN: __ c2bool(rax);            break;
2076   case T_CHAR   : __ andptr(rax, 0xFFFF);    break;
2077   case T_BYTE   : __ sign_extend_byte (rax); break;
2078   case T_SHORT  : __ sign_extend_short(rax); break;
2079   case T_INT    : /* nothing to do */        break;
2080   case T_DOUBLE :
2081   case T_FLOAT  :
2082     // Result is in st0 we'll save as needed
2083     break;
2084   case T_ARRAY:                 // Really a handle
2085   case T_OBJECT:                // Really a handle
2086       break; // can't de-handlize until after safepoint check
2087   case T_VOID: break;
2088   case T_LONG: break;
2089   default       : ShouldNotReachHere();
2090   }
2091 
2092   // Switch thread to "native transition" state before reading the synchronization state.
2093   // This additional state is necessary because reading and testing the synchronization
2094   // state is not atomic w.r.t. GC, as this scenario demonstrates:
2095   //     Java thread A, in _thread_in_native state, loads _not_synchronized and is preempted.
2096   //     VM thread changes sync state to synchronizing and suspends threads for GC.
2097   //     Thread A is resumed to finish this native method, but doesn't block here since it
2098   //     didn't see any synchronization is progress, and escapes.
2099   __ movl(Address(thread, JavaThread::thread_state_offset()), _thread_in_native_trans);
2100 
2101   if(os::is_MP()) {
2102     if (UseMembar) {
2103       // Force this write out before the read below
2104       __ membar(Assembler::Membar_mask_bits(
2105            Assembler::LoadLoad | Assembler::LoadStore |
2106            Assembler::StoreLoad | Assembler::StoreStore));
2107     } else {
2108       // Write serialization page so VM thread can do a pseudo remote membar.
2109       // We use the current thread pointer to calculate a thread specific
2110       // offset to write to within the page. This minimizes bus traffic
2111       // due to cache line collision.
2112       __ serialize_memory(thread, rcx);
2113     }
2114   }
2115 
2116   if (AlwaysRestoreFPU) {
2117     // Make sure the control word is correct.
2118     __ fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_std()));
2119   }
2120 
2121   Label after_transition;
2122 
2123   // check for safepoint operation in progress and/or pending suspend requests
2124   { Label Continue;
2125 
2126     __ cmp32(ExternalAddress((address)SafepointSynchronize::address_of_state()),
2127              SafepointSynchronize::_not_synchronized);
2128 
2129     Label L;
2130     __ jcc(Assembler::notEqual, L);
2131     __ cmpl(Address(thread, JavaThread::suspend_flags_offset()), 0);
2132     __ jcc(Assembler::equal, Continue);
2133     __ bind(L);
2134 
2135     // Don't use call_VM as it will see a possible pending exception and forward it
2136     // and never return here preventing us from clearing _last_native_pc down below.
2137     // Also can't use call_VM_leaf either as it will check to see if rsi & rdi are
2138     // preserved and correspond to the bcp/locals pointers. So we do a runtime call
2139     // by hand.
2140     //
2141     save_native_result(masm, ret_type, stack_slots);
2142     __ push(thread);
2143     if (!is_critical_native) {
2144       __ call(RuntimeAddress(CAST_FROM_FN_PTR(address,
2145                                               JavaThread::check_special_condition_for_native_trans)));
2146     } else {
2147       __ call(RuntimeAddress(CAST_FROM_FN_PTR(address,
2148                                               JavaThread::check_special_condition_for_native_trans_and_transition)));
2149     }
2150     __ increment(rsp, wordSize);
2151     // Restore any method result value
2152     restore_native_result(masm, ret_type, stack_slots);
2153 
2154     if (is_critical_native) {
2155       // The call above performed the transition to thread_in_Java so
2156       // skip the transition logic below.
2157       __ jmpb(after_transition);
2158     }
2159 
2160     __ bind(Continue);
2161   }
2162 
2163   // change thread state
2164   __ movl(Address(thread, JavaThread::thread_state_offset()), _thread_in_Java);
2165   __ bind(after_transition);
2166 
2167   Label reguard;
2168   Label reguard_done;
2169   __ cmpl(Address(thread, JavaThread::stack_guard_state_offset()), JavaThread::stack_guard_yellow_disabled);
2170   __ jcc(Assembler::equal, reguard);
2171 
2172   // slow path reguard  re-enters here
2173   __ bind(reguard_done);
2174 
2175   // Handle possible exception (will unlock if necessary)
2176 
2177   // native result if any is live
2178 
2179   // Unlock
2180   Label slow_path_unlock;
2181   Label unlock_done;
2182   if (method->is_synchronized()) {
2183 
2184     Label done;
2185 
2186     // Get locked oop from the handle we passed to jni
2187     __ movptr(obj_reg, Address(oop_handle_reg, 0));
2188 
2189     if (UseBiasedLocking) {
2190       __ biased_locking_exit(obj_reg, rbx, done);
2191     }
2192 
2193     // Simple recursive lock?
2194 
2195     __ cmpptr(Address(rbp, lock_slot_rbp_offset), (int32_t)NULL_WORD);
2196     __ jcc(Assembler::equal, done);
2197 
2198     // Must save rax, if if it is live now because cmpxchg must use it
2199     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
2200       save_native_result(masm, ret_type, stack_slots);
2201     }
2202 
2203     //  get old displaced header
2204     __ movptr(rbx, Address(rbp, lock_slot_rbp_offset));
2205 
2206     // get address of the stack lock
2207     __ lea(rax, Address(rbp, lock_slot_rbp_offset));
2208 
2209     // Atomic swap old header if oop still contains the stack lock
2210     if (os::is_MP()) {
2211     __ lock();
2212     }
2213 
2214     // src -> dest iff dest == rax, else rax, <- dest
2215     // *obj_reg = rbx, iff *obj_reg == rax, else rax, = *(obj_reg)
2216     __ cmpxchgptr(rbx, Address(obj_reg, 0));
2217     __ jcc(Assembler::notEqual, slow_path_unlock);
2218 
2219     // slow path re-enters here
2220     __ bind(unlock_done);
2221     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
2222       restore_native_result(masm, ret_type, stack_slots);
2223     }
2224 
2225     __ bind(done);
2226 
2227   }
2228 
2229   {
2230     SkipIfEqual skip_if(masm, &DTraceMethodProbes, 0);
2231     // Tell dtrace about this method exit
2232     save_native_result(masm, ret_type, stack_slots);
2233     __ mov_metadata(rax, method());
2234     __ call_VM_leaf(
2235          CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit),
2236          thread, rax);
2237     restore_native_result(masm, ret_type, stack_slots);
2238   }
2239 
2240   // We can finally stop using that last_Java_frame we setup ages ago
2241 
2242   __ reset_last_Java_frame(thread, false, true);
2243 
2244   // Unpack oop result
2245   if (ret_type == T_OBJECT || ret_type == T_ARRAY) {
2246       Label L;
2247       __ cmpptr(rax, (int32_t)NULL_WORD);
2248       __ jcc(Assembler::equal, L);
2249       __ movptr(rax, Address(rax, 0));
2250       __ bind(L);
2251       __ verify_oop(rax);
2252   }
2253 
2254   if (!is_critical_native) {
2255     // reset handle block
2256     __ movptr(rcx, Address(thread, JavaThread::active_handles_offset()));
2257     __ movl(Address(rcx, JNIHandleBlock::top_offset_in_bytes()), NULL_WORD);
2258 
2259     // Any exception pending?
2260     __ cmpptr(Address(thread, in_bytes(Thread::pending_exception_offset())), (int32_t)NULL_WORD);
2261     __ jcc(Assembler::notEqual, exception_pending);
2262   }
2263 
2264   // no exception, we're almost done
2265 
2266   // check that only result value is on FPU stack
2267   __ verify_FPU(ret_type == T_FLOAT || ret_type == T_DOUBLE ? 1 : 0, "native_wrapper normal exit");
2268 
2269   // Fixup floating pointer results so that result looks like a return from a compiled method
2270   if (ret_type == T_FLOAT) {
2271     if (UseSSE >= 1) {
2272       // Pop st0 and store as float and reload into xmm register
2273       __ fstp_s(Address(rbp, -4));
2274       __ movflt(xmm0, Address(rbp, -4));
2275     }
2276   } else if (ret_type == T_DOUBLE) {
2277     if (UseSSE >= 2) {
2278       // Pop st0 and store as double and reload into xmm register
2279       __ fstp_d(Address(rbp, -8));
2280       __ movdbl(xmm0, Address(rbp, -8));
2281     }
2282   }
2283 
2284   // Return
2285 
2286   __ leave();
2287   __ ret(0);
2288 
2289   // Unexpected paths are out of line and go here
2290 
2291   // Slow path locking & unlocking
2292   if (method->is_synchronized()) {
2293 
2294     // BEGIN Slow path lock
2295 
2296     __ bind(slow_path_lock);
2297 
2298     // has last_Java_frame setup. No exceptions so do vanilla call not call_VM
2299     // args are (oop obj, BasicLock* lock, JavaThread* thread)
2300     __ push(thread);
2301     __ push(lock_reg);
2302     __ push(obj_reg);
2303     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_locking_C)));
2304     __ addptr(rsp, 3*wordSize);
2305 
2306 #ifdef ASSERT
2307     { Label L;
2308     __ cmpptr(Address(thread, in_bytes(Thread::pending_exception_offset())), (int)NULL_WORD);
2309     __ jcc(Assembler::equal, L);
2310     __ stop("no pending exception allowed on exit from monitorenter");
2311     __ bind(L);
2312     }
2313 #endif
2314     __ jmp(lock_done);
2315 
2316     // END Slow path lock
2317 
2318     // BEGIN Slow path unlock
2319     __ bind(slow_path_unlock);
2320 
2321     // Slow path unlock
2322 
2323     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2324       save_native_result(masm, ret_type, stack_slots);
2325     }
2326     // Save pending exception around call to VM (which contains an EXCEPTION_MARK)
2327 
2328     __ pushptr(Address(thread, in_bytes(Thread::pending_exception_offset())));
2329     __ movptr(Address(thread, in_bytes(Thread::pending_exception_offset())), NULL_WORD);
2330 
2331 
2332     // should be a peal
2333     // +wordSize because of the push above
2334     // args are (oop obj, BasicLock* lock, JavaThread* thread)
2335     __ push(thread);
2336     __ lea(rax, Address(rbp, lock_slot_rbp_offset));
2337     __ push(rax);
2338 
2339     __ push(obj_reg);
2340     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C)));
2341     __ addptr(rsp, 3*wordSize);
2342 #ifdef ASSERT
2343     {
2344       Label L;
2345       __ cmpptr(Address(thread, in_bytes(Thread::pending_exception_offset())), (int32_t)NULL_WORD);
2346       __ jcc(Assembler::equal, L);
2347       __ stop("no pending exception allowed on exit complete_monitor_unlocking_C");
2348       __ bind(L);
2349     }
2350 #endif /* ASSERT */
2351 
2352     __ popptr(Address(thread, in_bytes(Thread::pending_exception_offset())));
2353 
2354     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2355       restore_native_result(masm, ret_type, stack_slots);
2356     }
2357     __ jmp(unlock_done);
2358     // END Slow path unlock
2359 
2360   }
2361 
2362   // SLOW PATH Reguard the stack if needed
2363 
2364   __ bind(reguard);
2365   save_native_result(masm, ret_type, stack_slots);
2366   {
2367     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages)));
2368   }
2369   restore_native_result(masm, ret_type, stack_slots);
2370   __ jmp(reguard_done);
2371 
2372 
2373   // BEGIN EXCEPTION PROCESSING
2374 
2375   if (!is_critical_native) {
2376     // Forward  the exception
2377     __ bind(exception_pending);
2378 
2379     // remove possible return value from FPU register stack
2380     __ empty_FPU_stack();
2381 
2382     // pop our frame
2383     __ leave();
2384     // and forward the exception
2385     __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2386   }
2387 
2388   __ flush();
2389 
2390   nmethod *nm = nmethod::new_native_nmethod(method,
2391                                             compile_id,
2392                                             masm->code(),
2393                                             vep_offset,
2394                                             frame_complete,
2395                                             stack_slots / VMRegImpl::slots_per_word,
2396                                             (is_static ? in_ByteSize(klass_offset) : in_ByteSize(receiver_offset)),
2397                                             in_ByteSize(lock_slot_offset*VMRegImpl::stack_slot_size),
2398                                             oop_maps);
2399 
2400   if (is_critical_native) {
2401     nm->set_lazy_critical_native(true);
2402   }
2403 
2404   return nm;
2405 
2406 }
2407 
2408 // this function returns the adjust size (in number of words) to a c2i adapter
2409 // activation for use during deoptimization
2410 int Deoptimization::last_frame_adjust(int callee_parameters, int callee_locals ) {
2411   return (callee_locals - callee_parameters) * Interpreter::stackElementWords;
2412 }
2413 
2414 
2415 uint SharedRuntime::out_preserve_stack_slots() {
2416   return 0;
2417 }
2418 
2419 //------------------------------generate_deopt_blob----------------------------
2420 void SharedRuntime::generate_deopt_blob() {
2421   // allocate space for the code
2422   ResourceMark rm;
2423   // setup code generation tools
2424   // note: the buffer code size must account for StackShadowPages=50
2425   CodeBuffer   buffer("deopt_blob", 1536, 1024);
2426   MacroAssembler* masm = new MacroAssembler(&buffer);
2427   int frame_size_in_words;
2428   OopMap* map = NULL;
2429   // Account for the extra args we place on the stack
2430   // by the time we call fetch_unroll_info
2431   const int additional_words = 2; // deopt kind, thread
2432 
2433   OopMapSet *oop_maps = new OopMapSet();
2434 
2435   // -------------
2436   // This code enters when returning to a de-optimized nmethod.  A return
2437   // address has been pushed on the the stack, and return values are in
2438   // registers.
2439   // If we are doing a normal deopt then we were called from the patched
2440   // nmethod from the point we returned to the nmethod. So the return
2441   // address on the stack is wrong by NativeCall::instruction_size
2442   // We will adjust the value to it looks like we have the original return
2443   // address on the stack (like when we eagerly deoptimized).
2444   // In the case of an exception pending with deoptimized then we enter
2445   // with a return address on the stack that points after the call we patched
2446   // into the exception handler. We have the following register state:
2447   //    rax,: exception
2448   //    rbx,: exception handler
2449   //    rdx: throwing pc
2450   // So in this case we simply jam rdx into the useless return address and
2451   // the stack looks just like we want.
2452   //
2453   // At this point we need to de-opt.  We save the argument return
2454   // registers.  We call the first C routine, fetch_unroll_info().  This
2455   // routine captures the return values and returns a structure which
2456   // describes the current frame size and the sizes of all replacement frames.
2457   // The current frame is compiled code and may contain many inlined
2458   // functions, each with their own JVM state.  We pop the current frame, then
2459   // push all the new frames.  Then we call the C routine unpack_frames() to
2460   // populate these frames.  Finally unpack_frames() returns us the new target
2461   // address.  Notice that callee-save registers are BLOWN here; they have
2462   // already been captured in the vframeArray at the time the return PC was
2463   // patched.
2464   address start = __ pc();
2465   Label cont;
2466 
2467   // Prolog for non exception case!
2468 
2469   // Save everything in sight.
2470 
2471   map = RegisterSaver::save_live_registers(masm, additional_words, &frame_size_in_words, false);
2472   // Normal deoptimization
2473   __ push(Deoptimization::Unpack_deopt);
2474   __ jmp(cont);
2475 
2476   int reexecute_offset = __ pc() - start;
2477 
2478   // Reexecute case
2479   // return address is the pc describes what bci to do re-execute at
2480 
2481   // No need to update map as each call to save_live_registers will produce identical oopmap
2482   (void) RegisterSaver::save_live_registers(masm, additional_words, &frame_size_in_words, false);
2483 
2484   __ push(Deoptimization::Unpack_reexecute);
2485   __ jmp(cont);
2486 
2487   int exception_offset = __ pc() - start;
2488 
2489   // Prolog for exception case
2490 
2491   // all registers are dead at this entry point, except for rax, and
2492   // rdx which contain the exception oop and exception pc
2493   // respectively.  Set them in TLS and fall thru to the
2494   // unpack_with_exception_in_tls entry point.
2495 
2496   __ get_thread(rdi);
2497   __ movptr(Address(rdi, JavaThread::exception_pc_offset()), rdx);
2498   __ movptr(Address(rdi, JavaThread::exception_oop_offset()), rax);
2499 
2500   int exception_in_tls_offset = __ pc() - start;
2501 
2502   // new implementation because exception oop is now passed in JavaThread
2503 
2504   // Prolog for exception case
2505   // All registers must be preserved because they might be used by LinearScan
2506   // Exceptiop oop and throwing PC are passed in JavaThread
2507   // tos: stack at point of call to method that threw the exception (i.e. only
2508   // args are on the stack, no return address)
2509 
2510   // make room on stack for the return address
2511   // It will be patched later with the throwing pc. The correct value is not
2512   // available now because loading it from memory would destroy registers.
2513   __ push(0);
2514 
2515   // Save everything in sight.
2516 
2517   // No need to update map as each call to save_live_registers will produce identical oopmap
2518   (void) RegisterSaver::save_live_registers(masm, additional_words, &frame_size_in_words, false);
2519 
2520   // Now it is safe to overwrite any register
2521 
2522   // store the correct deoptimization type
2523   __ push(Deoptimization::Unpack_exception);
2524 
2525   // load throwing pc from JavaThread and patch it as the return address
2526   // of the current frame. Then clear the field in JavaThread
2527   __ get_thread(rdi);
2528   __ movptr(rdx, Address(rdi, JavaThread::exception_pc_offset()));
2529   __ movptr(Address(rbp, wordSize), rdx);
2530   __ movptr(Address(rdi, JavaThread::exception_pc_offset()), NULL_WORD);
2531 
2532 #ifdef ASSERT
2533   // verify that there is really an exception oop in JavaThread
2534   __ movptr(rax, Address(rdi, JavaThread::exception_oop_offset()));
2535   __ verify_oop(rax);
2536 
2537   // verify that there is no pending exception
2538   Label no_pending_exception;
2539   __ movptr(rax, Address(rdi, Thread::pending_exception_offset()));
2540   __ testptr(rax, rax);
2541   __ jcc(Assembler::zero, no_pending_exception);
2542   __ stop("must not have pending exception here");
2543   __ bind(no_pending_exception);
2544 #endif
2545 
2546   __ bind(cont);
2547 
2548   // Compiled code leaves the floating point stack dirty, empty it.
2549   __ empty_FPU_stack();
2550 
2551 
2552   // Call C code.  Need thread and this frame, but NOT official VM entry
2553   // crud.  We cannot block on this call, no GC can happen.
2554   __ get_thread(rcx);
2555   __ push(rcx);
2556   // fetch_unroll_info needs to call last_java_frame()
2557   __ set_last_Java_frame(rcx, noreg, noreg, NULL);
2558 
2559   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::fetch_unroll_info)));
2560 
2561   // Need to have an oopmap that tells fetch_unroll_info where to
2562   // find any register it might need.
2563 
2564   oop_maps->add_gc_map( __ pc()-start, map);
2565 
2566   // Discard arg to fetch_unroll_info
2567   __ pop(rcx);
2568 
2569   __ get_thread(rcx);
2570   __ reset_last_Java_frame(rcx, false, false);
2571 
2572   // Load UnrollBlock into EDI
2573   __ mov(rdi, rax);
2574 
2575   // Move the unpack kind to a safe place in the UnrollBlock because
2576   // we are very short of registers
2577 
2578   Address unpack_kind(rdi, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes());
2579   // retrieve the deopt kind from where we left it.
2580   __ pop(rax);
2581   __ movl(unpack_kind, rax);                      // save the unpack_kind value
2582 
2583    Label noException;
2584   __ cmpl(rax, Deoptimization::Unpack_exception);   // Was exception pending?
2585   __ jcc(Assembler::notEqual, noException);
2586   __ movptr(rax, Address(rcx, JavaThread::exception_oop_offset()));
2587   __ movptr(rdx, Address(rcx, JavaThread::exception_pc_offset()));
2588   __ movptr(Address(rcx, JavaThread::exception_oop_offset()), NULL_WORD);
2589   __ movptr(Address(rcx, JavaThread::exception_pc_offset()), NULL_WORD);
2590 
2591   __ verify_oop(rax);
2592 
2593   // Overwrite the result registers with the exception results.
2594   __ movptr(Address(rsp, RegisterSaver::raxOffset()*wordSize), rax);
2595   __ movptr(Address(rsp, RegisterSaver::rdxOffset()*wordSize), rdx);
2596 
2597   __ bind(noException);
2598 
2599   // Stack is back to only having register save data on the stack.
2600   // Now restore the result registers. Everything else is either dead or captured
2601   // in the vframeArray.
2602 
2603   RegisterSaver::restore_result_registers(masm);
2604 
2605   // Non standard control word may be leaked out through a safepoint blob, and we can
2606   // deopt at a poll point with the non standard control word. However, we should make
2607   // sure the control word is correct after restore_result_registers.
2608   __ fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_std()));
2609 
2610   // All of the register save area has been popped of the stack. Only the
2611   // return address remains.
2612 
2613   // Pop all the frames we must move/replace.
2614   //
2615   // Frame picture (youngest to oldest)
2616   // 1: self-frame (no frame link)
2617   // 2: deopting frame  (no frame link)
2618   // 3: caller of deopting frame (could be compiled/interpreted).
2619   //
2620   // Note: by leaving the return address of self-frame on the stack
2621   // and using the size of frame 2 to adjust the stack
2622   // when we are done the return to frame 3 will still be on the stack.
2623 
2624   // Pop deoptimized frame
2625   __ addptr(rsp, Address(rdi,Deoptimization::UnrollBlock::size_of_deoptimized_frame_offset_in_bytes()));
2626 
2627   // sp should be pointing at the return address to the caller (3)
2628 
2629   // Pick up the initial fp we should save
2630   // restore rbp before stack bang because if stack overflow is thrown it needs to be pushed (and preserved)
2631   __ movptr(rbp, Address(rdi, Deoptimization::UnrollBlock::initial_info_offset_in_bytes()));
2632 
2633 #ifdef ASSERT
2634   // Compilers generate code that bang the stack by as much as the
2635   // interpreter would need. So this stack banging should never
2636   // trigger a fault. Verify that it does not on non product builds.
2637   if (UseStackBanging) {
2638     __ movl(rbx, Address(rdi ,Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes()));
2639     __ bang_stack_size(rbx, rcx);
2640   }
2641 #endif
2642 
2643   // Load array of frame pcs into ECX
2644   __ movptr(rcx,Address(rdi,Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2645 
2646   __ pop(rsi); // trash the old pc
2647 
2648   // Load array of frame sizes into ESI
2649   __ movptr(rsi,Address(rdi,Deoptimization::UnrollBlock::frame_sizes_offset_in_bytes()));
2650 
2651   Address counter(rdi, Deoptimization::UnrollBlock::counter_temp_offset_in_bytes());
2652 
2653   __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock::number_of_frames_offset_in_bytes()));
2654   __ movl(counter, rbx);
2655 
2656   // Now adjust the caller's stack to make up for the extra locals
2657   // but record the original sp so that we can save it in the skeletal interpreter
2658   // frame and the stack walking of interpreter_sender will get the unextended sp
2659   // value and not the "real" sp value.
2660 
2661   Address sp_temp(rdi, Deoptimization::UnrollBlock::sender_sp_temp_offset_in_bytes());
2662   __ movptr(sp_temp, rsp);
2663   __ movl2ptr(rbx, Address(rdi, Deoptimization::UnrollBlock::caller_adjustment_offset_in_bytes()));
2664   __ subptr(rsp, rbx);
2665 
2666   // Push interpreter frames in a loop
2667   Label loop;
2668   __ bind(loop);
2669   __ movptr(rbx, Address(rsi, 0));      // Load frame size
2670 #ifdef CC_INTERP
2671   __ subptr(rbx, 4*wordSize);           // we'll push pc and ebp by hand and
2672 #ifdef ASSERT
2673   __ push(0xDEADDEAD);                  // Make a recognizable pattern
2674   __ push(0xDEADDEAD);
2675 #else /* ASSERT */
2676   __ subptr(rsp, 2*wordSize);           // skip the "static long no_param"
2677 #endif /* ASSERT */
2678 #else /* CC_INTERP */
2679   __ subptr(rbx, 2*wordSize);           // we'll push pc and rbp, by hand
2680 #endif /* CC_INTERP */
2681   __ pushptr(Address(rcx, 0));          // save return address
2682   __ enter();                           // save old & set new rbp,
2683   __ subptr(rsp, rbx);                  // Prolog!
2684   __ movptr(rbx, sp_temp);              // sender's sp
2685 #ifdef CC_INTERP
2686   __ movptr(Address(rbp,
2687                   -(sizeof(BytecodeInterpreter)) + in_bytes(byte_offset_of(BytecodeInterpreter, _sender_sp))),
2688           rbx); // Make it walkable
2689 #else /* CC_INTERP */
2690   // This value is corrected by layout_activation_impl
2691   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
2692   __ movptr(Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize), rbx); // Make it walkable
2693 #endif /* CC_INTERP */
2694   __ movptr(sp_temp, rsp);              // pass to next frame
2695   __ addptr(rsi, wordSize);             // Bump array pointer (sizes)
2696   __ addptr(rcx, wordSize);             // Bump array pointer (pcs)
2697   __ decrementl(counter);             // decrement counter
2698   __ jcc(Assembler::notZero, loop);
2699   __ pushptr(Address(rcx, 0));          // save final return address
2700 
2701   // Re-push self-frame
2702   __ enter();                           // save old & set new rbp,
2703 
2704   //  Return address and rbp, are in place
2705   // We'll push additional args later. Just allocate a full sized
2706   // register save area
2707   __ subptr(rsp, (frame_size_in_words-additional_words - 2) * wordSize);
2708 
2709   // Restore frame locals after moving the frame
2710   __ movptr(Address(rsp, RegisterSaver::raxOffset()*wordSize), rax);
2711   __ movptr(Address(rsp, RegisterSaver::rdxOffset()*wordSize), rdx);
2712   __ fstp_d(Address(rsp, RegisterSaver::fpResultOffset()*wordSize));   // Pop float stack and store in local
2713   if( UseSSE>=2 ) __ movdbl(Address(rsp, RegisterSaver::xmm0Offset()*wordSize), xmm0);
2714   if( UseSSE==1 ) __ movflt(Address(rsp, RegisterSaver::xmm0Offset()*wordSize), xmm0);
2715 
2716   // Set up the args to unpack_frame
2717 
2718   __ pushl(unpack_kind);                     // get the unpack_kind value
2719   __ get_thread(rcx);
2720   __ push(rcx);
2721 
2722   // set last_Java_sp, last_Java_fp
2723   __ set_last_Java_frame(rcx, noreg, rbp, NULL);
2724 
2725   // Call C code.  Need thread but NOT official VM entry
2726   // crud.  We cannot block on this call, no GC can happen.  Call should
2727   // restore return values to their stack-slots with the new SP.
2728   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2729   // Set an oopmap for the call site
2730   oop_maps->add_gc_map( __ pc()-start, new OopMap( frame_size_in_words, 0 ));
2731 
2732   // rax, contains the return result type
2733   __ push(rax);
2734 
2735   __ get_thread(rcx);
2736   __ reset_last_Java_frame(rcx, false, false);
2737 
2738   // Collect return values
2739   __ movptr(rax,Address(rsp, (RegisterSaver::raxOffset() + additional_words + 1)*wordSize));
2740   __ movptr(rdx,Address(rsp, (RegisterSaver::rdxOffset() + additional_words + 1)*wordSize));
2741 
2742   // Clear floating point stack before returning to interpreter
2743   __ empty_FPU_stack();
2744 
2745   // Check if we should push the float or double return value.
2746   Label results_done, yes_double_value;
2747   __ cmpl(Address(rsp, 0), T_DOUBLE);
2748   __ jcc (Assembler::zero, yes_double_value);
2749   __ cmpl(Address(rsp, 0), T_FLOAT);
2750   __ jcc (Assembler::notZero, results_done);
2751 
2752   // return float value as expected by interpreter
2753   if( UseSSE>=1 ) __ movflt(xmm0, Address(rsp, (RegisterSaver::xmm0Offset() + additional_words + 1)*wordSize));
2754   else            __ fld_d(Address(rsp, (RegisterSaver::fpResultOffset() + additional_words + 1)*wordSize));
2755   __ jmp(results_done);
2756 
2757   // return double value as expected by interpreter
2758   __ bind(yes_double_value);
2759   if( UseSSE>=2 ) __ movdbl(xmm0, Address(rsp, (RegisterSaver::xmm0Offset() + additional_words + 1)*wordSize));
2760   else            __ fld_d(Address(rsp, (RegisterSaver::fpResultOffset() + additional_words + 1)*wordSize));
2761 
2762   __ bind(results_done);
2763 
2764   // Pop self-frame.
2765   __ leave();                              // Epilog!
2766 
2767   // Jump to interpreter
2768   __ ret(0);
2769 
2770   // -------------
2771   // make sure all code is generated
2772   masm->flush();
2773 
2774   _deopt_blob = DeoptimizationBlob::create( &buffer, oop_maps, 0, exception_offset, reexecute_offset, frame_size_in_words);
2775   _deopt_blob->set_unpack_with_exception_in_tls_offset(exception_in_tls_offset);
2776 }
2777 
2778 
2779 #ifdef COMPILER2
2780 //------------------------------generate_uncommon_trap_blob--------------------
2781 void SharedRuntime::generate_uncommon_trap_blob() {
2782   // allocate space for the code
2783   ResourceMark rm;
2784   // setup code generation tools
2785   CodeBuffer   buffer("uncommon_trap_blob", 512, 512);
2786   MacroAssembler* masm = new MacroAssembler(&buffer);
2787 
2788   enum frame_layout {
2789     arg0_off,      // thread                     sp + 0 // Arg location for
2790     arg1_off,      // unloaded_class_index       sp + 1 // calling C
2791     // The frame sender code expects that rbp will be in the "natural" place and
2792     // will override any oopMap setting for it. We must therefore force the layout
2793     // so that it agrees with the frame sender code.
2794     rbp_off,       // callee saved register      sp + 2
2795     return_off,    // slot for return address    sp + 3
2796     framesize
2797   };
2798 
2799   address start = __ pc();
2800 
2801   if (UseRTMLocking) {
2802     // Abort RTM transaction before possible nmethod deoptimization.
2803     __ xabort(0);
2804   }
2805 
2806   // Push self-frame.
2807   __ subptr(rsp, return_off*wordSize);     // Epilog!
2808 
2809   // rbp, is an implicitly saved callee saved register (i.e. the calling
2810   // convention will save restore it in prolog/epilog) Other than that
2811   // there are no callee save registers no that adapter frames are gone.
2812   __ movptr(Address(rsp, rbp_off*wordSize), rbp);
2813 
2814   // Clear the floating point exception stack
2815   __ empty_FPU_stack();
2816 
2817   // set last_Java_sp
2818   __ get_thread(rdx);
2819   __ set_last_Java_frame(rdx, noreg, noreg, NULL);
2820 
2821   // Call C code.  Need thread but NOT official VM entry
2822   // crud.  We cannot block on this call, no GC can happen.  Call should
2823   // capture callee-saved registers as well as return values.
2824   __ movptr(Address(rsp, arg0_off*wordSize), rdx);
2825   // argument already in ECX
2826   __ movl(Address(rsp, arg1_off*wordSize),rcx);
2827   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::uncommon_trap)));
2828 
2829   // Set an oopmap for the call site
2830   OopMapSet *oop_maps = new OopMapSet();
2831   OopMap* map =  new OopMap( framesize, 0 );
2832   // No oopMap for rbp, it is known implicitly
2833 
2834   oop_maps->add_gc_map( __ pc()-start, map);
2835 
2836   __ get_thread(rcx);
2837 
2838   __ reset_last_Java_frame(rcx, false, false);
2839 
2840   // Load UnrollBlock into EDI
2841   __ movptr(rdi, rax);
2842 
2843   // Pop all the frames we must move/replace.
2844   //
2845   // Frame picture (youngest to oldest)
2846   // 1: self-frame (no frame link)
2847   // 2: deopting frame  (no frame link)
2848   // 3: caller of deopting frame (could be compiled/interpreted).
2849 
2850   // Pop self-frame.  We have no frame, and must rely only on EAX and ESP.
2851   __ addptr(rsp,(framesize-1)*wordSize);     // Epilog!
2852 
2853   // Pop deoptimized frame
2854   __ movl2ptr(rcx, Address(rdi,Deoptimization::UnrollBlock::size_of_deoptimized_frame_offset_in_bytes()));
2855   __ addptr(rsp, rcx);
2856 
2857   // sp should be pointing at the return address to the caller (3)
2858 
2859   // Pick up the initial fp we should save
2860   // restore rbp before stack bang because if stack overflow is thrown it needs to be pushed (and preserved)
2861   __ movptr(rbp, Address(rdi, Deoptimization::UnrollBlock::initial_info_offset_in_bytes()));
2862 
2863 #ifdef ASSERT
2864   // Compilers generate code that bang the stack by as much as the
2865   // interpreter would need. So this stack banging should never
2866   // trigger a fault. Verify that it does not on non product builds.
2867   if (UseStackBanging) {
2868     __ movl(rbx, Address(rdi ,Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes()));
2869     __ bang_stack_size(rbx, rcx);
2870   }
2871 #endif
2872 
2873   // Load array of frame pcs into ECX
2874   __ movl(rcx,Address(rdi,Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2875 
2876   __ pop(rsi); // trash the pc
2877 
2878   // Load array of frame sizes into ESI
2879   __ movptr(rsi,Address(rdi,Deoptimization::UnrollBlock::frame_sizes_offset_in_bytes()));
2880 
2881   Address counter(rdi, Deoptimization::UnrollBlock::counter_temp_offset_in_bytes());
2882 
2883   __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock::number_of_frames_offset_in_bytes()));
2884   __ movl(counter, rbx);
2885 
2886   // Now adjust the caller's stack to make up for the extra locals
2887   // but record the original sp so that we can save it in the skeletal interpreter
2888   // frame and the stack walking of interpreter_sender will get the unextended sp
2889   // value and not the "real" sp value.
2890 
2891   Address sp_temp(rdi, Deoptimization::UnrollBlock::sender_sp_temp_offset_in_bytes());
2892   __ movptr(sp_temp, rsp);
2893   __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock::caller_adjustment_offset_in_bytes()));
2894   __ subptr(rsp, rbx);
2895 
2896   // Push interpreter frames in a loop
2897   Label loop;
2898   __ bind(loop);
2899   __ movptr(rbx, Address(rsi, 0));      // Load frame size
2900 #ifdef CC_INTERP
2901   __ subptr(rbx, 4*wordSize);           // we'll push pc and ebp by hand and
2902 #ifdef ASSERT
2903   __ push(0xDEADDEAD);                  // Make a recognizable pattern
2904   __ push(0xDEADDEAD);                  // (parm to RecursiveInterpreter...)
2905 #else /* ASSERT */
2906   __ subptr(rsp, 2*wordSize);           // skip the "static long no_param"
2907 #endif /* ASSERT */
2908 #else /* CC_INTERP */
2909   __ subptr(rbx, 2*wordSize);           // we'll push pc and rbp, by hand
2910 #endif /* CC_INTERP */
2911   __ pushptr(Address(rcx, 0));          // save return address
2912   __ enter();                           // save old & set new rbp,
2913   __ subptr(rsp, rbx);                  // Prolog!
2914   __ movptr(rbx, sp_temp);              // sender's sp
2915 #ifdef CC_INTERP
2916   __ movptr(Address(rbp,
2917                   -(sizeof(BytecodeInterpreter)) + in_bytes(byte_offset_of(BytecodeInterpreter, _sender_sp))),
2918           rbx); // Make it walkable
2919 #else /* CC_INTERP */
2920   // This value is corrected by layout_activation_impl
2921   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD );
2922   __ movptr(Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize), rbx); // Make it walkable
2923 #endif /* CC_INTERP */
2924   __ movptr(sp_temp, rsp);              // pass to next frame
2925   __ addptr(rsi, wordSize);             // Bump array pointer (sizes)
2926   __ addptr(rcx, wordSize);             // Bump array pointer (pcs)
2927   __ decrementl(counter);             // decrement counter
2928   __ jcc(Assembler::notZero, loop);
2929   __ pushptr(Address(rcx, 0));            // save final return address
2930 
2931   // Re-push self-frame
2932   __ enter();                           // save old & set new rbp,
2933   __ subptr(rsp, (framesize-2) * wordSize);   // Prolog!
2934 
2935 
2936   // set last_Java_sp, last_Java_fp
2937   __ get_thread(rdi);
2938   __ set_last_Java_frame(rdi, noreg, rbp, NULL);
2939 
2940   // Call C code.  Need thread but NOT official VM entry
2941   // crud.  We cannot block on this call, no GC can happen.  Call should
2942   // restore return values to their stack-slots with the new SP.
2943   __ movptr(Address(rsp,arg0_off*wordSize),rdi);
2944   __ movl(Address(rsp,arg1_off*wordSize), Deoptimization::Unpack_uncommon_trap);
2945   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2946   // Set an oopmap for the call site
2947   oop_maps->add_gc_map( __ pc()-start, new OopMap( framesize, 0 ) );
2948 
2949   __ get_thread(rdi);
2950   __ reset_last_Java_frame(rdi, true, false);
2951 
2952   // Pop self-frame.
2953   __ leave();     // Epilog!
2954 
2955   // Jump to interpreter
2956   __ ret(0);
2957 
2958   // -------------
2959   // make sure all code is generated
2960   masm->flush();
2961 
2962    _uncommon_trap_blob = UncommonTrapBlob::create(&buffer, oop_maps, framesize);
2963 }
2964 #endif // COMPILER2
2965 
2966 //------------------------------generate_handler_blob------
2967 //
2968 // Generate a special Compile2Runtime blob that saves all registers,
2969 // setup oopmap, and calls safepoint code to stop the compiled code for
2970 // a safepoint.
2971 //
2972 SafepointBlob* SharedRuntime::generate_handler_blob(address call_ptr, int poll_type) {
2973 
2974   // Account for thread arg in our frame
2975   const int additional_words = 1;
2976   int frame_size_in_words;
2977 
2978   assert (StubRoutines::forward_exception_entry() != NULL, "must be generated before");
2979 
2980   ResourceMark rm;
2981   OopMapSet *oop_maps = new OopMapSet();
2982   OopMap* map;
2983 
2984   // allocate space for the code
2985   // setup code generation tools
2986   CodeBuffer   buffer("handler_blob", 1024, 512);
2987   MacroAssembler* masm = new MacroAssembler(&buffer);
2988 
2989   const Register java_thread = rdi; // callee-saved for VC++
2990   address start   = __ pc();
2991   address call_pc = NULL;
2992   bool cause_return = (poll_type == POLL_AT_RETURN);
2993   bool save_vectors = (poll_type == POLL_AT_VECTOR_LOOP);
2994 
2995   if (UseRTMLocking) {
2996     // Abort RTM transaction before calling runtime
2997     // because critical section will be large and will be
2998     // aborted anyway. Also nmethod could be deoptimized.
2999     __ xabort(0);
3000   }
3001 
3002   // If cause_return is true we are at a poll_return and there is
3003   // the return address on the stack to the caller on the nmethod
3004   // that is safepoint. We can leave this return on the stack and
3005   // effectively complete the return and safepoint in the caller.
3006   // Otherwise we push space for a return address that the safepoint
3007   // handler will install later to make the stack walking sensible.
3008   if (!cause_return)
3009     __ push(rbx);  // Make room for return address (or push it again)
3010 
3011   map = RegisterSaver::save_live_registers(masm, additional_words, &frame_size_in_words, false, save_vectors);
3012 
3013   // The following is basically a call_VM. However, we need the precise
3014   // address of the call in order to generate an oopmap. Hence, we do all the
3015   // work ourselves.
3016 
3017   // Push thread argument and setup last_Java_sp
3018   __ get_thread(java_thread);
3019   __ push(java_thread);
3020   __ set_last_Java_frame(java_thread, noreg, noreg, NULL);
3021 
3022   // if this was not a poll_return then we need to correct the return address now.
3023   if (!cause_return) {
3024     __ movptr(rax, Address(java_thread, JavaThread::saved_exception_pc_offset()));
3025     __ movptr(Address(rbp, wordSize), rax);
3026   }
3027 
3028   // do the call
3029   __ call(RuntimeAddress(call_ptr));
3030 
3031   // Set an oopmap for the call site.  This oopmap will map all
3032   // oop-registers and debug-info registers as callee-saved.  This
3033   // will allow deoptimization at this safepoint to find all possible
3034   // debug-info recordings, as well as let GC find all oops.
3035 
3036   oop_maps->add_gc_map( __ pc() - start, map);
3037 
3038   // Discard arg
3039   __ pop(rcx);
3040 
3041   Label noException;
3042 
3043   // Clear last_Java_sp again
3044   __ get_thread(java_thread);
3045   __ reset_last_Java_frame(java_thread, false, false);
3046 
3047   __ cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
3048   __ jcc(Assembler::equal, noException);
3049 
3050   // Exception pending
3051   RegisterSaver::restore_live_registers(masm, save_vectors);
3052 
3053   __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3054 
3055   __ bind(noException);
3056 
3057   // Normal exit, register restoring and exit
3058   RegisterSaver::restore_live_registers(masm, save_vectors);
3059 
3060   __ ret(0);
3061 
3062   // make sure all code is generated
3063   masm->flush();
3064 
3065   // Fill-out other meta info
3066   return SafepointBlob::create(&buffer, oop_maps, frame_size_in_words);
3067 }
3068 
3069 //
3070 // generate_resolve_blob - call resolution (static/virtual/opt-virtual/ic-miss
3071 //
3072 // Generate a stub that calls into vm to find out the proper destination
3073 // of a java call. All the argument registers are live at this point
3074 // but since this is generic code we don't know what they are and the caller
3075 // must do any gc of the args.
3076 //
3077 RuntimeStub* SharedRuntime::generate_resolve_blob(address destination, const char* name) {
3078   assert (StubRoutines::forward_exception_entry() != NULL, "must be generated before");
3079 
3080   // allocate space for the code
3081   ResourceMark rm;
3082 
3083   CodeBuffer buffer(name, 1000, 512);
3084   MacroAssembler* masm                = new MacroAssembler(&buffer);
3085 
3086   int frame_size_words;
3087   enum frame_layout {
3088                 thread_off,
3089                 extra_words };
3090 
3091   OopMapSet *oop_maps = new OopMapSet();
3092   OopMap* map = NULL;
3093 
3094   int start = __ offset();
3095 
3096   map = RegisterSaver::save_live_registers(masm, extra_words, &frame_size_words);
3097 
3098   int frame_complete = __ offset();
3099 
3100   const Register thread = rdi;
3101   __ get_thread(rdi);
3102 
3103   __ push(thread);
3104   __ set_last_Java_frame(thread, noreg, rbp, NULL);
3105 
3106   __ call(RuntimeAddress(destination));
3107 
3108 
3109   // Set an oopmap for the call site.
3110   // We need this not only for callee-saved registers, but also for volatile
3111   // registers that the compiler might be keeping live across a safepoint.
3112 
3113   oop_maps->add_gc_map( __ offset() - start, map);
3114 
3115   // rax, contains the address we are going to jump to assuming no exception got installed
3116 
3117   __ addptr(rsp, wordSize);
3118 
3119   // clear last_Java_sp
3120   __ reset_last_Java_frame(thread, true, false);
3121   // check for pending exceptions
3122   Label pending;
3123   __ cmpptr(Address(thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
3124   __ jcc(Assembler::notEqual, pending);
3125 
3126   // get the returned Method*
3127   __ get_vm_result_2(rbx, thread);
3128   __ movptr(Address(rsp, RegisterSaver::rbx_offset() * wordSize), rbx);
3129 
3130   __ movptr(Address(rsp, RegisterSaver::rax_offset() * wordSize), rax);
3131 
3132   RegisterSaver::restore_live_registers(masm);
3133 
3134   // We are back the the original state on entry and ready to go.
3135 
3136   __ jmp(rax);
3137 
3138   // Pending exception after the safepoint
3139 
3140   __ bind(pending);
3141 
3142   RegisterSaver::restore_live_registers(masm);
3143 
3144   // exception pending => remove activation and forward to exception handler
3145 
3146   __ get_thread(thread);
3147   __ movptr(Address(thread, JavaThread::vm_result_offset()), NULL_WORD);
3148   __ movptr(rax, Address(thread, Thread::pending_exception_offset()));
3149   __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3150 
3151   // -------------
3152   // make sure all code is generated
3153   masm->flush();
3154 
3155   // return the  blob
3156   // frame_size_words or bytes??
3157   return RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, frame_size_words, oop_maps, true);
3158 }