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