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