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