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