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 void SharedRuntime::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   // Note: rsi contains the senderSP on entry. We must preserve it since
 743   // we may do a i2c -> c2i transition if we lose a race where compiled
 744   // code goes non-entrant while we get args ready.
 745 
 746   // Adapters can be frameless because they do not require the caller
 747   // to perform additional cleanup work, such as correcting the stack pointer.
 748   // An i2c adapter is frameless because the *caller* frame, which is interpreted,
 749   // routinely repairs its own stack pointer (from interpreter_frame_last_sp),
 750   // even if a callee has modified the stack pointer.
 751   // A c2i adapter is frameless because the *callee* frame, which is interpreted,
 752   // routinely repairs its caller's stack pointer (from sender_sp, which is set
 753   // up via the senderSP register).
 754   // In other words, if *either* the caller or callee is interpreted, we can
 755   // get the stack pointer repaired after a call.
 756   // This is why c2i and i2c adapters cannot be indefinitely composed.
 757   // In particular, if a c2i adapter were to somehow call an i2c adapter,
 758   // both caller and callee would be compiled methods, and neither would
 759   // clean up the stack pointer changes performed by the two adapters.
 760   // If this happens, control eventually transfers back to the compiled
 761   // caller, but with an uncorrected stack, causing delayed havoc.
 762 
 763   // Pick up the return address
 764   __ movptr(rax, Address(rsp, 0));
 765 
 766   if (VerifyAdapterCalls &&
 767       (Interpreter::code() != NULL || StubRoutines::code1() != NULL)) {
 768     // So, let's test for cascading c2i/i2c adapters right now.
 769     //  assert(Interpreter::contains($return_addr) ||
 770     //         StubRoutines::contains($return_addr),
 771     //         "i2c adapter must return to an interpreter frame");
 772     __ block_comment("verify_i2c { ");
 773     Label L_ok;
 774     if (Interpreter::code() != NULL)
 775       range_check(masm, rax, rdi,
 776                   Interpreter::code()->code_start(), Interpreter::code()->code_end(),
 777                   L_ok);
 778     if (StubRoutines::code1() != NULL)
 779       range_check(masm, rax, rdi,
 780                   StubRoutines::code1()->code_begin(), StubRoutines::code1()->code_end(),
 781                   L_ok);
 782     if (StubRoutines::code2() != NULL)
 783       range_check(masm, rax, rdi,
 784                   StubRoutines::code2()->code_begin(), StubRoutines::code2()->code_end(),
 785                   L_ok);
 786     const char* msg = "i2c adapter must return to an interpreter frame";
 787     __ block_comment(msg);
 788     __ stop(msg);
 789     __ bind(L_ok);
 790     __ block_comment("} verify_i2ce ");
 791   }
 792 
 793   // Must preserve original SP for loading incoming arguments because
 794   // we need to align the outgoing SP for compiled code.
 795   __ movptr(rdi, rsp);
 796 
 797   // Cut-out for having no stack args.  Since up to 2 int/oop args are passed
 798   // in registers, we will occasionally have no stack args.
 799   int comp_words_on_stack = 0;
 800   if (comp_args_on_stack) {
 801     // Sig words on the stack are greater-than VMRegImpl::stack0.  Those in
 802     // registers are below.  By subtracting stack0, we either get a negative
 803     // number (all values in registers) or the maximum stack slot accessed.
 804     // int comp_args_on_stack = VMRegImpl::reg2stack(max_arg);
 805     // Convert 4-byte stack slots to words.
 806     comp_words_on_stack = round_to(comp_args_on_stack*4, wordSize)>>LogBytesPerWord;
 807     // Round up to miminum stack alignment, in wordSize
 808     comp_words_on_stack = round_to(comp_words_on_stack, 2);
 809     __ subptr(rsp, comp_words_on_stack * wordSize);
 810   }
 811 
 812   // Align the outgoing SP
 813   __ andptr(rsp, -(StackAlignmentInBytes));
 814 
 815   // push the return address on the stack (note that pushing, rather
 816   // than storing it, yields the correct frame alignment for the callee)
 817   __ push(rax);
 818 
 819   // Put saved SP in another register
 820   const Register saved_sp = rax;
 821   __ movptr(saved_sp, rdi);
 822 
 823 
 824   // Will jump to the compiled code just as if compiled code was doing it.
 825   // Pre-load the register-jump target early, to schedule it better.
 826   __ movptr(rdi, Address(rbx, in_bytes(Method::from_compiled_offset())));
 827 
 828   // Now generate the shuffle code.  Pick up all register args and move the
 829   // rest through the floating point stack top.
 830   for (int i = 0; i < total_args_passed; i++) {
 831     if (sig_bt[i] == T_VOID) {
 832       // Longs and doubles are passed in native word order, but misaligned
 833       // in the 32-bit build.
 834       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
 835       continue;
 836     }
 837 
 838     // Pick up 0, 1 or 2 words from SP+offset.
 839 
 840     assert(!regs[i].second()->is_valid() || regs[i].first()->next() == regs[i].second(),
 841             "scrambled load targets?");
 842     // Load in argument order going down.
 843     int ld_off = (total_args_passed - i) * Interpreter::stackElementSize;
 844     // Point to interpreter value (vs. tag)
 845     int next_off = ld_off - Interpreter::stackElementSize;
 846     //
 847     //
 848     //
 849     VMReg r_1 = regs[i].first();
 850     VMReg r_2 = regs[i].second();
 851     if (!r_1->is_valid()) {
 852       assert(!r_2->is_valid(), "");
 853       continue;
 854     }
 855     if (r_1->is_stack()) {
 856       // Convert stack slot to an SP offset (+ wordSize to account for return address )
 857       int st_off = regs[i].first()->reg2stack()*VMRegImpl::stack_slot_size + wordSize;
 858 
 859       // We can use rsi as a temp here because compiled code doesn't need rsi as an input
 860       // and if we end up going thru a c2i because of a miss a reasonable value of rsi
 861       // we be generated.
 862       if (!r_2->is_valid()) {
 863         // __ fld_s(Address(saved_sp, ld_off));
 864         // __ fstp_s(Address(rsp, st_off));
 865         __ movl(rsi, Address(saved_sp, ld_off));
 866         __ movptr(Address(rsp, st_off), rsi);
 867       } else {
 868         // Interpreter local[n] == MSW, local[n+1] == LSW however locals
 869         // are accessed as negative so LSW is at LOW address
 870 
 871         // ld_off is MSW so get LSW
 872         // st_off is LSW (i.e. reg.first())
 873         // __ fld_d(Address(saved_sp, next_off));
 874         // __ fstp_d(Address(rsp, st_off));
 875         //
 876         // We are using two VMRegs. This can be either T_OBJECT, T_ADDRESS, T_LONG, or T_DOUBLE
 877         // the interpreter allocates two slots but only uses one for thr T_LONG or T_DOUBLE case
 878         // So we must adjust where to pick up the data to match the interpreter.
 879         //
 880         // Interpreter local[n] == MSW, local[n+1] == LSW however locals
 881         // are accessed as negative so LSW is at LOW address
 882 
 883         // ld_off is MSW so get LSW
 884         const int offset = (NOT_LP64(true ||) sig_bt[i]==T_LONG||sig_bt[i]==T_DOUBLE)?
 885                            next_off : ld_off;
 886         __ movptr(rsi, Address(saved_sp, offset));
 887         __ movptr(Address(rsp, st_off), rsi);
 888 #ifndef _LP64
 889         __ movptr(rsi, Address(saved_sp, ld_off));
 890         __ movptr(Address(rsp, st_off + wordSize), rsi);
 891 #endif // _LP64
 892       }
 893     } else if (r_1->is_Register()) {  // Register argument
 894       Register r = r_1->as_Register();
 895       assert(r != rax, "must be different");
 896       if (r_2->is_valid()) {
 897         //
 898         // We are using two VMRegs. This can be either T_OBJECT, T_ADDRESS, T_LONG, or T_DOUBLE
 899         // the interpreter allocates two slots but only uses one for thr T_LONG or T_DOUBLE case
 900         // So we must adjust where to pick up the data to match the interpreter.
 901 
 902         const int offset = (NOT_LP64(true ||) sig_bt[i]==T_LONG||sig_bt[i]==T_DOUBLE)?
 903                            next_off : ld_off;
 904 
 905         // this can be a misaligned move
 906         __ movptr(r, Address(saved_sp, offset));
 907 #ifndef _LP64
 908         assert(r_2->as_Register() != rax, "need another temporary register");
 909         // Remember r_1 is low address (and LSB on x86)
 910         // So r_2 gets loaded from high address regardless of the platform
 911         __ movptr(r_2->as_Register(), Address(saved_sp, ld_off));
 912 #endif // _LP64
 913       } else {
 914         __ movl(r, Address(saved_sp, ld_off));
 915       }
 916     } else {
 917       assert(r_1->is_XMMRegister(), "");
 918       if (!r_2->is_valid()) {
 919         __ movflt(r_1->as_XMMRegister(), Address(saved_sp, ld_off));
 920       } else {
 921         move_i2c_double(masm, r_1->as_XMMRegister(), saved_sp, ld_off);
 922       }
 923     }
 924   }
 925 
 926   // 6243940 We might end up in handle_wrong_method if
 927   // the callee is deoptimized as we race thru here. If that
 928   // happens we don't want to take a safepoint because the
 929   // caller frame will look interpreted and arguments are now
 930   // "compiled" so it is much better to make this transition
 931   // invisible to the stack walking code. Unfortunately if
 932   // we try and find the callee by normal means a safepoint
 933   // is possible. So we stash the desired callee in the thread
 934   // and the vm will find there should this case occur.
 935 
 936   __ get_thread(rax);
 937   __ movptr(Address(rax, JavaThread::callee_target_offset()), rbx);
 938 
 939   // move Method* to rax, in case we end up in an c2i adapter.
 940   // the c2i adapters expect Method* in rax, (c2) because c2's
 941   // resolve stubs return the result (the method) in rax,.
 942   // I'd love to fix this.
 943   __ mov(rax, rbx);
 944 
 945   __ jmp(rdi);
 946 }
 947 
 948 // ---------------------------------------------------------------
 949 AdapterHandlerEntry* SharedRuntime::generate_i2c2i_adapters(MacroAssembler *masm,
 950                                                             int total_args_passed,
 951                                                             int comp_args_on_stack,
 952                                                             const BasicType *sig_bt,
 953                                                             const VMRegPair *regs,
 954                                                             AdapterFingerPrint* fingerprint) {
 955   address i2c_entry = __ pc();
 956 
 957   gen_i2c_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs);
 958 
 959   // -------------------------------------------------------------------------
 960   // Generate a C2I adapter.  On entry we know rbx, holds the Method* during calls
 961   // to the interpreter.  The args start out packed in the compiled layout.  They
 962   // need to be unpacked into the interpreter layout.  This will almost always
 963   // require some stack space.  We grow the current (compiled) stack, then repack
 964   // the args.  We  finally end in a jump to the generic interpreter entry point.
 965   // On exit from the interpreter, the interpreter will restore our SP (lest the
 966   // compiled code, which relys solely on SP and not EBP, get sick).
 967 
 968   address c2i_unverified_entry = __ pc();
 969   Label skip_fixup;
 970 
 971   Register holder = rax;
 972   Register receiver = rcx;
 973   Register temp = rbx;
 974 
 975   {
 976 
 977     Label missed;
 978     __ movptr(temp, Address(receiver, oopDesc::klass_offset_in_bytes()));
 979     __ cmpptr(temp, Address(holder, CompiledICHolder::holder_klass_offset()));
 980     __ movptr(rbx, Address(holder, CompiledICHolder::holder_method_offset()));
 981     __ jcc(Assembler::notEqual, missed);
 982     // Method might have been compiled since the call site was patched to
 983     // interpreted if that is the case treat it as a miss so we can get
 984     // the call site corrected.
 985     __ cmpptr(Address(rbx, in_bytes(Method::code_offset())), (int32_t)NULL_WORD);
 986     __ jcc(Assembler::equal, skip_fixup);
 987 
 988     __ bind(missed);
 989     __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 990   }
 991 
 992   address c2i_entry = __ pc();
 993 
 994   gen_c2i_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs, skip_fixup);
 995 
 996   __ flush();
 997   return AdapterHandlerLibrary::new_entry(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry);
 998 }
 999 
1000 int SharedRuntime::c_calling_convention(const BasicType *sig_bt,
1001                                          VMRegPair *regs,
1002                                          VMRegPair *regs2,
1003                                          int total_args_passed) {
1004   assert(regs2 == NULL, "not needed on x86");
1005 // We return the amount of VMRegImpl stack slots we need to reserve for all
1006 // the arguments NOT counting out_preserve_stack_slots.
1007 
1008   uint    stack = 0;        // All arguments on stack
1009 
1010   for( int i = 0; i < total_args_passed; i++) {
1011     // From the type and the argument number (count) compute the location
1012     switch( sig_bt[i] ) {
1013     case T_BOOLEAN:
1014     case T_CHAR:
1015     case T_FLOAT:
1016     case T_BYTE:
1017     case T_SHORT:
1018     case T_INT:
1019     case T_OBJECT:
1020     case T_ARRAY:
1021     case T_ADDRESS:
1022     case T_METADATA:
1023       regs[i].set1(VMRegImpl::stack2reg(stack++));
1024       break;
1025     case T_LONG:
1026     case T_DOUBLE: // The stack numbering is reversed from Java
1027       // Since C arguments do not get reversed, the ordering for
1028       // doubles on the stack must be opposite the Java convention
1029       assert(sig_bt[i+1] == T_VOID, "missing Half" );
1030       regs[i].set2(VMRegImpl::stack2reg(stack));
1031       stack += 2;
1032       break;
1033     case T_VOID: regs[i].set_bad(); break;
1034     default:
1035       ShouldNotReachHere();
1036       break;
1037     }
1038   }
1039   return stack;
1040 }
1041 
1042 // A simple move of integer like type
1043 static void simple_move32(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1044   if (src.first()->is_stack()) {
1045     if (dst.first()->is_stack()) {
1046       // stack to stack
1047       // __ ld(FP, reg2offset(src.first()) + STACK_BIAS, L5);
1048       // __ st(L5, SP, reg2offset(dst.first()) + STACK_BIAS);
1049       __ movl2ptr(rax, Address(rbp, reg2offset_in(src.first())));
1050       __ movptr(Address(rsp, reg2offset_out(dst.first())), rax);
1051     } else {
1052       // stack to reg
1053       __ movl2ptr(dst.first()->as_Register(),  Address(rbp, reg2offset_in(src.first())));
1054     }
1055   } else if (dst.first()->is_stack()) {
1056     // reg to stack
1057     // no need to sign extend on 64bit
1058     __ movptr(Address(rsp, reg2offset_out(dst.first())), src.first()->as_Register());
1059   } else {
1060     if (dst.first() != src.first()) {
1061       __ mov(dst.first()->as_Register(), src.first()->as_Register());
1062     }
1063   }
1064 }
1065 
1066 // An oop arg. Must pass a handle not the oop itself
1067 static void object_move(MacroAssembler* masm,
1068                         OopMap* map,
1069                         int oop_handle_offset,
1070                         int framesize_in_slots,
1071                         VMRegPair src,
1072                         VMRegPair dst,
1073                         bool is_receiver,
1074                         int* receiver_offset) {
1075 
1076   // Because of the calling conventions we know that src can be a
1077   // register or a stack location. dst can only be a stack location.
1078 
1079   assert(dst.first()->is_stack(), "must be stack");
1080   // must pass a handle. First figure out the location we use as a handle
1081 
1082   if (src.first()->is_stack()) {
1083     // Oop is already on the stack as an argument
1084     Register rHandle = rax;
1085     Label nil;
1086     __ xorptr(rHandle, rHandle);
1087     __ cmpptr(Address(rbp, reg2offset_in(src.first())), (int32_t)NULL_WORD);
1088     __ jcc(Assembler::equal, nil);
1089     __ lea(rHandle, Address(rbp, reg2offset_in(src.first())));
1090     __ bind(nil);
1091     __ movptr(Address(rsp, reg2offset_out(dst.first())), rHandle);
1092 
1093     int offset_in_older_frame = src.first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
1094     map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + framesize_in_slots));
1095     if (is_receiver) {
1096       *receiver_offset = (offset_in_older_frame + framesize_in_slots) * VMRegImpl::stack_slot_size;
1097     }
1098   } else {
1099     // Oop is in an a register we must store it to the space we reserve
1100     // on the stack for oop_handles
1101     const Register rOop = src.first()->as_Register();
1102     const Register rHandle = rax;
1103     int oop_slot = (rOop == rcx ? 0 : 1) * VMRegImpl::slots_per_word + oop_handle_offset;
1104     int offset = oop_slot*VMRegImpl::stack_slot_size;
1105     Label skip;
1106     __ movptr(Address(rsp, offset), rOop);
1107     map->set_oop(VMRegImpl::stack2reg(oop_slot));
1108     __ xorptr(rHandle, rHandle);
1109     __ cmpptr(rOop, (int32_t)NULL_WORD);
1110     __ jcc(Assembler::equal, skip);
1111     __ lea(rHandle, Address(rsp, offset));
1112     __ bind(skip);
1113     // Store the handle parameter
1114     __ movptr(Address(rsp, reg2offset_out(dst.first())), rHandle);
1115     if (is_receiver) {
1116       *receiver_offset = offset;
1117     }
1118   }
1119 }
1120 
1121 // A float arg may have to do float reg int reg conversion
1122 static void float_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1123   assert(!src.second()->is_valid() && !dst.second()->is_valid(), "bad float_move");
1124 
1125   // Because of the calling convention we know that src is either a stack location
1126   // or an xmm register. dst can only be a stack location.
1127 
1128   assert(dst.first()->is_stack() && ( src.first()->is_stack() || src.first()->is_XMMRegister()), "bad parameters");
1129 
1130   if (src.first()->is_stack()) {
1131     __ movl(rax, Address(rbp, reg2offset_in(src.first())));
1132     __ movptr(Address(rsp, reg2offset_out(dst.first())), rax);
1133   } else {
1134     // reg to stack
1135     __ movflt(Address(rsp, reg2offset_out(dst.first())), src.first()->as_XMMRegister());
1136   }
1137 }
1138 
1139 // A long move
1140 static void long_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1141 
1142   // The only legal possibility for a long_move VMRegPair is:
1143   // 1: two stack slots (possibly unaligned)
1144   // as neither the java  or C calling convention will use registers
1145   // for longs.
1146 
1147   if (src.first()->is_stack() && dst.first()->is_stack()) {
1148     assert(src.second()->is_stack() && dst.second()->is_stack(), "must be all stack");
1149     __ movptr(rax, Address(rbp, reg2offset_in(src.first())));
1150     NOT_LP64(__ movptr(rbx, Address(rbp, reg2offset_in(src.second()))));
1151     __ movptr(Address(rsp, reg2offset_out(dst.first())), rax);
1152     NOT_LP64(__ movptr(Address(rsp, reg2offset_out(dst.second())), rbx));
1153   } else {
1154     ShouldNotReachHere();
1155   }
1156 }
1157 
1158 // A double move
1159 static void double_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1160 
1161   // The only legal possibilities for a double_move VMRegPair are:
1162   // The painful thing here is that like long_move a VMRegPair might be
1163 
1164   // Because of the calling convention we know that src is either
1165   //   1: a single physical register (xmm registers only)
1166   //   2: two stack slots (possibly unaligned)
1167   // dst can only be a pair of stack slots.
1168 
1169   assert(dst.first()->is_stack() && (src.first()->is_XMMRegister() || src.first()->is_stack()), "bad args");
1170 
1171   if (src.first()->is_stack()) {
1172     // source is all stack
1173     __ movptr(rax, Address(rbp, reg2offset_in(src.first())));
1174     NOT_LP64(__ movptr(rbx, Address(rbp, reg2offset_in(src.second()))));
1175     __ movptr(Address(rsp, reg2offset_out(dst.first())), rax);
1176     NOT_LP64(__ movptr(Address(rsp, reg2offset_out(dst.second())), rbx));
1177   } else {
1178     // reg to stack
1179     // No worries about stack alignment
1180     __ movdbl(Address(rsp, reg2offset_out(dst.first())), src.first()->as_XMMRegister());
1181   }
1182 }
1183 
1184 
1185 void SharedRuntime::save_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1186   // We always ignore the frame_slots arg and just use the space just below frame pointer
1187   // which by this time is free to use
1188   switch (ret_type) {
1189   case T_FLOAT:
1190     __ fstp_s(Address(rbp, -wordSize));
1191     break;
1192   case T_DOUBLE:
1193     __ fstp_d(Address(rbp, -2*wordSize));
1194     break;
1195   case T_VOID:  break;
1196   case T_LONG:
1197     __ movptr(Address(rbp, -wordSize), rax);
1198     NOT_LP64(__ movptr(Address(rbp, -2*wordSize), rdx));
1199     break;
1200   default: {
1201     __ movptr(Address(rbp, -wordSize), rax);
1202     }
1203   }
1204 }
1205 
1206 void SharedRuntime::restore_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1207   // We always ignore the frame_slots arg and just use the space just below frame pointer
1208   // which by this time is free to use
1209   switch (ret_type) {
1210   case T_FLOAT:
1211     __ fld_s(Address(rbp, -wordSize));
1212     break;
1213   case T_DOUBLE:
1214     __ fld_d(Address(rbp, -2*wordSize));
1215     break;
1216   case T_LONG:
1217     __ movptr(rax, Address(rbp, -wordSize));
1218     NOT_LP64(__ movptr(rdx, Address(rbp, -2*wordSize)));
1219     break;
1220   case T_VOID:  break;
1221   default: {
1222     __ movptr(rax, Address(rbp, -wordSize));
1223     }
1224   }
1225 }
1226 
1227 
1228 static void save_or_restore_arguments(MacroAssembler* masm,
1229                                       const int stack_slots,
1230                                       const int total_in_args,
1231                                       const int arg_save_area,
1232                                       OopMap* map,
1233                                       VMRegPair* in_regs,
1234                                       BasicType* in_sig_bt) {
1235   // if map is non-NULL then the code should store the values,
1236   // otherwise it should load them.
1237   int handle_index = 0;
1238   // Save down double word first
1239   for ( int i = 0; i < total_in_args; i++) {
1240     if (in_regs[i].first()->is_XMMRegister() && in_sig_bt[i] == T_DOUBLE) {
1241       int slot = handle_index * VMRegImpl::slots_per_word + arg_save_area;
1242       int offset = slot * VMRegImpl::stack_slot_size;
1243       handle_index += 2;
1244       assert(handle_index <= stack_slots, "overflow");
1245       if (map != NULL) {
1246         __ movdbl(Address(rsp, offset), in_regs[i].first()->as_XMMRegister());
1247       } else {
1248         __ movdbl(in_regs[i].first()->as_XMMRegister(), Address(rsp, offset));
1249       }
1250     }
1251     if (in_regs[i].first()->is_Register() && in_sig_bt[i] == T_LONG) {
1252       int slot = handle_index * VMRegImpl::slots_per_word + arg_save_area;
1253       int offset = slot * VMRegImpl::stack_slot_size;
1254       handle_index += 2;
1255       assert(handle_index <= stack_slots, "overflow");
1256       if (map != NULL) {
1257         __ movl(Address(rsp, offset), in_regs[i].first()->as_Register());
1258         if (in_regs[i].second()->is_Register()) {
1259           __ movl(Address(rsp, offset + 4), in_regs[i].second()->as_Register());
1260         }
1261       } else {
1262         __ movl(in_regs[i].first()->as_Register(), Address(rsp, offset));
1263         if (in_regs[i].second()->is_Register()) {
1264           __ movl(in_regs[i].second()->as_Register(), Address(rsp, offset + 4));
1265         }
1266       }
1267     }
1268   }
1269   // Save or restore single word registers
1270   for ( int i = 0; i < total_in_args; i++) {
1271     if (in_regs[i].first()->is_Register()) {
1272       int slot = handle_index++ * VMRegImpl::slots_per_word + arg_save_area;
1273       int offset = slot * VMRegImpl::stack_slot_size;
1274       assert(handle_index <= stack_slots, "overflow");
1275       if (in_sig_bt[i] == T_ARRAY && map != NULL) {
1276         map->set_oop(VMRegImpl::stack2reg(slot));;
1277       }
1278 
1279       // Value is in an input register pass we must flush it to the stack
1280       const Register reg = in_regs[i].first()->as_Register();
1281       switch (in_sig_bt[i]) {
1282         case T_ARRAY:
1283           if (map != NULL) {
1284             __ movptr(Address(rsp, offset), reg);
1285           } else {
1286             __ movptr(reg, Address(rsp, offset));
1287           }
1288           break;
1289         case T_BOOLEAN:
1290         case T_CHAR:
1291         case T_BYTE:
1292         case T_SHORT:
1293         case T_INT:
1294           if (map != NULL) {
1295             __ movl(Address(rsp, offset), reg);
1296           } else {
1297             __ movl(reg, Address(rsp, offset));
1298           }
1299           break;
1300         case T_OBJECT:
1301         default: ShouldNotReachHere();
1302       }
1303     } else if (in_regs[i].first()->is_XMMRegister()) {
1304       if (in_sig_bt[i] == T_FLOAT) {
1305         int slot = handle_index++ * VMRegImpl::slots_per_word + arg_save_area;
1306         int offset = slot * VMRegImpl::stack_slot_size;
1307         assert(handle_index <= stack_slots, "overflow");
1308         if (map != NULL) {
1309           __ movflt(Address(rsp, offset), in_regs[i].first()->as_XMMRegister());
1310         } else {
1311           __ movflt(in_regs[i].first()->as_XMMRegister(), Address(rsp, offset));
1312         }
1313       }
1314     } else if (in_regs[i].first()->is_stack()) {
1315       if (in_sig_bt[i] == T_ARRAY && map != NULL) {
1316         int offset_in_older_frame = in_regs[i].first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
1317         map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + stack_slots));
1318       }
1319     }
1320   }
1321 }
1322 
1323 // Check GC_locker::needs_gc and enter the runtime if it's true.  This
1324 // keeps a new JNI critical region from starting until a GC has been
1325 // forced.  Save down any oops in registers and describe them in an
1326 // OopMap.
1327 static void check_needs_gc_for_critical_native(MacroAssembler* masm,
1328                                                Register thread,
1329                                                int stack_slots,
1330                                                int total_c_args,
1331                                                int total_in_args,
1332                                                int arg_save_area,
1333                                                OopMapSet* oop_maps,
1334                                                VMRegPair* in_regs,
1335                                                BasicType* in_sig_bt) {
1336   __ block_comment("check GC_locker::needs_gc");
1337   Label cont;
1338   __ cmp8(ExternalAddress((address)GC_locker::needs_gc_address()), false);
1339   __ jcc(Assembler::equal, cont);
1340 
1341   // Save down any incoming oops and call into the runtime to halt for a GC
1342 
1343   OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1344 
1345   save_or_restore_arguments(masm, stack_slots, total_in_args,
1346                             arg_save_area, map, in_regs, in_sig_bt);
1347 
1348   address the_pc = __ pc();
1349   oop_maps->add_gc_map( __ offset(), map);
1350   __ set_last_Java_frame(thread, rsp, noreg, the_pc);
1351 
1352   __ block_comment("block_for_jni_critical");
1353   __ push(thread);
1354   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::block_for_jni_critical)));
1355   __ increment(rsp, wordSize);
1356 
1357   __ get_thread(thread);
1358   __ reset_last_Java_frame(thread, false, true);
1359 
1360   save_or_restore_arguments(masm, stack_slots, total_in_args,
1361                             arg_save_area, NULL, in_regs, in_sig_bt);
1362 
1363   __ bind(cont);
1364 #ifdef ASSERT
1365   if (StressCriticalJNINatives) {
1366     // Stress register saving
1367     OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1368     save_or_restore_arguments(masm, stack_slots, total_in_args,
1369                               arg_save_area, map, in_regs, in_sig_bt);
1370     // Destroy argument registers
1371     for (int i = 0; i < total_in_args - 1; i++) {
1372       if (in_regs[i].first()->is_Register()) {
1373         const Register reg = in_regs[i].first()->as_Register();
1374         __ xorptr(reg, reg);
1375       } else if (in_regs[i].first()->is_XMMRegister()) {
1376         __ xorpd(in_regs[i].first()->as_XMMRegister(), in_regs[i].first()->as_XMMRegister());
1377       } else if (in_regs[i].first()->is_FloatRegister()) {
1378         ShouldNotReachHere();
1379       } else if (in_regs[i].first()->is_stack()) {
1380         // Nothing to do
1381       } else {
1382         ShouldNotReachHere();
1383       }
1384       if (in_sig_bt[i] == T_LONG || in_sig_bt[i] == T_DOUBLE) {
1385         i++;
1386       }
1387     }
1388 
1389     save_or_restore_arguments(masm, stack_slots, total_in_args,
1390                               arg_save_area, NULL, in_regs, in_sig_bt);
1391   }
1392 #endif
1393 }
1394 
1395 // Unpack an array argument into a pointer to the body and the length
1396 // if the array is non-null, otherwise pass 0 for both.
1397 static void unpack_array_argument(MacroAssembler* masm, VMRegPair reg, BasicType in_elem_type, VMRegPair body_arg, VMRegPair length_arg) {
1398   Register tmp_reg = rax;
1399   assert(!body_arg.first()->is_Register() || body_arg.first()->as_Register() != tmp_reg,
1400          "possible collision");
1401   assert(!length_arg.first()->is_Register() || length_arg.first()->as_Register() != tmp_reg,
1402          "possible collision");
1403 
1404   // Pass the length, ptr pair
1405   Label is_null, done;
1406   VMRegPair tmp(tmp_reg->as_VMReg());
1407   if (reg.first()->is_stack()) {
1408     // Load the arg up from the stack
1409     simple_move32(masm, reg, tmp);
1410     reg = tmp;
1411   }
1412   __ testptr(reg.first()->as_Register(), reg.first()->as_Register());
1413   __ jccb(Assembler::equal, is_null);
1414   __ lea(tmp_reg, Address(reg.first()->as_Register(), arrayOopDesc::base_offset_in_bytes(in_elem_type)));
1415   simple_move32(masm, tmp, body_arg);
1416   // load the length relative to the body.
1417   __ movl(tmp_reg, Address(tmp_reg, arrayOopDesc::length_offset_in_bytes() -
1418                            arrayOopDesc::base_offset_in_bytes(in_elem_type)));
1419   simple_move32(masm, tmp, length_arg);
1420   __ jmpb(done);
1421   __ bind(is_null);
1422   // Pass zeros
1423   __ xorptr(tmp_reg, tmp_reg);
1424   simple_move32(masm, tmp, body_arg);
1425   simple_move32(masm, tmp, length_arg);
1426   __ bind(done);
1427 }
1428 
1429 static void verify_oop_args(MacroAssembler* masm,
1430                             methodHandle method,
1431                             const BasicType* sig_bt,
1432                             const VMRegPair* regs) {
1433   Register temp_reg = rbx;  // not part of any compiled calling seq
1434   if (VerifyOops) {
1435     for (int i = 0; i < method->size_of_parameters(); i++) {
1436       if (sig_bt[i] == T_OBJECT ||
1437           sig_bt[i] == T_ARRAY) {
1438         VMReg r = regs[i].first();
1439         assert(r->is_valid(), "bad oop arg");
1440         if (r->is_stack()) {
1441           __ movptr(temp_reg, Address(rsp, r->reg2stack() * VMRegImpl::stack_slot_size + wordSize));
1442           __ verify_oop(temp_reg);
1443         } else {
1444           __ verify_oop(r->as_Register());
1445         }
1446       }
1447     }
1448   }
1449 }
1450 
1451 static void gen_special_dispatch(MacroAssembler* masm,
1452                                  methodHandle method,
1453                                  const BasicType* sig_bt,
1454                                  const VMRegPair* regs) {
1455   verify_oop_args(masm, method, sig_bt, regs);
1456   vmIntrinsics::ID iid = method->intrinsic_id();
1457 
1458   // Now write the args into the outgoing interpreter space
1459   bool     has_receiver   = false;
1460   Register receiver_reg   = noreg;
1461   int      member_arg_pos = -1;
1462   Register member_reg     = noreg;
1463   int      ref_kind       = MethodHandles::signature_polymorphic_intrinsic_ref_kind(iid);
1464   if (ref_kind != 0) {
1465     member_arg_pos = method->size_of_parameters() - 1;  // trailing MemberName argument
1466     member_reg = rbx;  // known to be free at this point
1467     has_receiver = MethodHandles::ref_kind_has_receiver(ref_kind);
1468   } else if (iid == vmIntrinsics::_invokeBasic) {
1469     has_receiver = true;
1470   } else {
1471     fatal(err_msg_res("unexpected intrinsic id %d", iid));
1472   }
1473 
1474   if (member_reg != noreg) {
1475     // Load the member_arg into register, if necessary.
1476     SharedRuntime::check_member_name_argument_is_last_argument(method, sig_bt, regs);
1477     VMReg r = regs[member_arg_pos].first();
1478     if (r->is_stack()) {
1479       __ movptr(member_reg, Address(rsp, r->reg2stack() * VMRegImpl::stack_slot_size + wordSize));
1480     } else {
1481       // no data motion is needed
1482       member_reg = r->as_Register();
1483     }
1484   }
1485 
1486   if (has_receiver) {
1487     // Make sure the receiver is loaded into a register.
1488     assert(method->size_of_parameters() > 0, "oob");
1489     assert(sig_bt[0] == T_OBJECT, "receiver argument must be an object");
1490     VMReg r = regs[0].first();
1491     assert(r->is_valid(), "bad receiver arg");
1492     if (r->is_stack()) {
1493       // Porting note:  This assumes that compiled calling conventions always
1494       // pass the receiver oop in a register.  If this is not true on some
1495       // platform, pick a temp and load the receiver from stack.
1496       fatal("receiver always in a register");
1497       receiver_reg = rcx;  // known to be free at this point
1498       __ movptr(receiver_reg, Address(rsp, r->reg2stack() * VMRegImpl::stack_slot_size + wordSize));
1499     } else {
1500       // no data motion is needed
1501       receiver_reg = r->as_Register();
1502     }
1503   }
1504 
1505   // Figure out which address we are really jumping to:
1506   MethodHandles::generate_method_handle_dispatch(masm, iid,
1507                                                  receiver_reg, member_reg, /*for_compiler_entry:*/ true);
1508 }
1509 
1510 // ---------------------------------------------------------------------------
1511 // Generate a native wrapper for a given method.  The method takes arguments
1512 // in the Java compiled code convention, marshals them to the native
1513 // convention (handlizes oops, etc), transitions to native, makes the call,
1514 // returns to java state (possibly blocking), unhandlizes any result and
1515 // returns.
1516 //
1517 // Critical native functions are a shorthand for the use of
1518 // GetPrimtiveArrayCritical and disallow the use of any other JNI
1519 // functions.  The wrapper is expected to unpack the arguments before
1520 // passing them to the callee and perform checks before and after the
1521 // native call to ensure that they GC_locker
1522 // lock_critical/unlock_critical semantics are followed.  Some other
1523 // parts of JNI setup are skipped like the tear down of the JNI handle
1524 // block and the check for pending exceptions it's impossible for them
1525 // to be thrown.
1526 //
1527 // They are roughly structured like this:
1528 //    if (GC_locker::needs_gc())
1529 //      SharedRuntime::block_for_jni_critical();
1530 //    tranistion to thread_in_native
1531 //    unpack arrray arguments and call native entry point
1532 //    check for safepoint in progress
1533 //    check if any thread suspend flags are set
1534 //      call into JVM and possible unlock the JNI critical
1535 //      if a GC was suppressed while in the critical native.
1536 //    transition back to thread_in_Java
1537 //    return to caller
1538 //
1539 nmethod* SharedRuntime::generate_native_wrapper(MacroAssembler* masm,
1540                                                 methodHandle method,
1541                                                 int compile_id,
1542                                                 BasicType* in_sig_bt,
1543                                                 VMRegPair* in_regs,
1544                                                 BasicType ret_type) {
1545   if (method->is_method_handle_intrinsic()) {
1546     vmIntrinsics::ID iid = method->intrinsic_id();
1547     intptr_t start = (intptr_t)__ pc();
1548     int vep_offset = ((intptr_t)__ pc()) - start;
1549     gen_special_dispatch(masm,
1550                          method,
1551                          in_sig_bt,
1552                          in_regs);
1553     int frame_complete = ((intptr_t)__ pc()) - start;  // not complete, period
1554     __ flush();
1555     int stack_slots = SharedRuntime::out_preserve_stack_slots();  // no out slots at all, actually
1556     return nmethod::new_native_nmethod(method,
1557                                        compile_id,
1558                                        masm->code(),
1559                                        vep_offset,
1560                                        frame_complete,
1561                                        stack_slots / VMRegImpl::slots_per_word,
1562                                        in_ByteSize(-1),
1563                                        in_ByteSize(-1),
1564                                        (OopMapSet*)NULL);
1565   }
1566   bool is_critical_native = true;
1567   address native_func = method->critical_native_function();
1568   if (native_func == NULL) {
1569     native_func = method->native_function();
1570     is_critical_native = false;
1571   }
1572   assert(native_func != NULL, "must have function");
1573 
1574   // An OopMap for lock (and class if static)
1575   OopMapSet *oop_maps = new OopMapSet();
1576 
1577   // We have received a description of where all the java arg are located
1578   // on entry to the wrapper. We need to convert these args to where
1579   // the jni function will expect them. To figure out where they go
1580   // we convert the java signature to a C signature by inserting
1581   // the hidden arguments as arg[0] and possibly arg[1] (static method)
1582 
1583   const int total_in_args = method->size_of_parameters();
1584   int total_c_args = total_in_args;
1585   if (!is_critical_native) {
1586     total_c_args += 1;
1587     if (method->is_static()) {
1588       total_c_args++;
1589     }
1590   } else {
1591     for (int i = 0; i < total_in_args; i++) {
1592       if (in_sig_bt[i] == T_ARRAY) {
1593         total_c_args++;
1594       }
1595     }
1596   }
1597 
1598   BasicType* out_sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_c_args);
1599   VMRegPair* out_regs   = NEW_RESOURCE_ARRAY(VMRegPair, total_c_args);
1600   BasicType* in_elem_bt = NULL;
1601 
1602   int argc = 0;
1603   if (!is_critical_native) {
1604     out_sig_bt[argc++] = T_ADDRESS;
1605     if (method->is_static()) {
1606       out_sig_bt[argc++] = T_OBJECT;
1607     }
1608 
1609     for (int i = 0; i < total_in_args ; i++ ) {
1610       out_sig_bt[argc++] = in_sig_bt[i];
1611     }
1612   } else {
1613     Thread* THREAD = Thread::current();
1614     in_elem_bt = NEW_RESOURCE_ARRAY(BasicType, total_in_args);
1615     SignatureStream ss(method->signature());
1616     for (int i = 0; i < total_in_args ; i++ ) {
1617       if (in_sig_bt[i] == T_ARRAY) {
1618         // Arrays are passed as int, elem* pair
1619         out_sig_bt[argc++] = T_INT;
1620         out_sig_bt[argc++] = T_ADDRESS;
1621         Symbol* atype = ss.as_symbol(CHECK_NULL);
1622         const char* at = atype->as_C_string();
1623         if (strlen(at) == 2) {
1624           assert(at[0] == '[', "must be");
1625           switch (at[1]) {
1626             case 'B': in_elem_bt[i]  = T_BYTE; break;
1627             case 'C': in_elem_bt[i]  = T_CHAR; break;
1628             case 'D': in_elem_bt[i]  = T_DOUBLE; break;
1629             case 'F': in_elem_bt[i]  = T_FLOAT; break;
1630             case 'I': in_elem_bt[i]  = T_INT; break;
1631             case 'J': in_elem_bt[i]  = T_LONG; break;
1632             case 'S': in_elem_bt[i]  = T_SHORT; break;
1633             case 'Z': in_elem_bt[i]  = T_BOOLEAN; break;
1634             default: ShouldNotReachHere();
1635           }
1636         }
1637       } else {
1638         out_sig_bt[argc++] = in_sig_bt[i];
1639         in_elem_bt[i] = T_VOID;
1640       }
1641       if (in_sig_bt[i] != T_VOID) {
1642         assert(in_sig_bt[i] == ss.type(), "must match");
1643         ss.next();
1644       }
1645     }
1646   }
1647 
1648   // Now figure out where the args must be stored and how much stack space
1649   // they require.
1650   int out_arg_slots;
1651   out_arg_slots = c_calling_convention(out_sig_bt, out_regs, NULL, total_c_args);
1652 
1653   // Compute framesize for the wrapper.  We need to handlize all oops in
1654   // registers a max of 2 on x86.
1655 
1656   // Calculate the total number of stack slots we will need.
1657 
1658   // First count the abi requirement plus all of the outgoing args
1659   int stack_slots = SharedRuntime::out_preserve_stack_slots() + out_arg_slots;
1660 
1661   // Now the space for the inbound oop handle area
1662   int total_save_slots = 2 * VMRegImpl::slots_per_word; // 2 arguments passed in registers
1663   if (is_critical_native) {
1664     // Critical natives may have to call out so they need a save area
1665     // for register arguments.
1666     int double_slots = 0;
1667     int single_slots = 0;
1668     for ( int i = 0; i < total_in_args; i++) {
1669       if (in_regs[i].first()->is_Register()) {
1670         const Register reg = in_regs[i].first()->as_Register();
1671         switch (in_sig_bt[i]) {
1672           case T_ARRAY:  // critical array (uses 2 slots on LP64)
1673           case T_BOOLEAN:
1674           case T_BYTE:
1675           case T_SHORT:
1676           case T_CHAR:
1677           case T_INT:  single_slots++; break;
1678           case T_LONG: double_slots++; break;
1679           default:  ShouldNotReachHere();
1680         }
1681       } else if (in_regs[i].first()->is_XMMRegister()) {
1682         switch (in_sig_bt[i]) {
1683           case T_FLOAT:  single_slots++; break;
1684           case T_DOUBLE: double_slots++; break;
1685           default:  ShouldNotReachHere();
1686         }
1687       } else if (in_regs[i].first()->is_FloatRegister()) {
1688         ShouldNotReachHere();
1689       }
1690     }
1691     total_save_slots = double_slots * 2 + single_slots;
1692     // align the save area
1693     if (double_slots != 0) {
1694       stack_slots = round_to(stack_slots, 2);
1695     }
1696   }
1697 
1698   int oop_handle_offset = stack_slots;
1699   stack_slots += total_save_slots;
1700 
1701   // Now any space we need for handlizing a klass if static method
1702 
1703   int klass_slot_offset = 0;
1704   int klass_offset = -1;
1705   int lock_slot_offset = 0;
1706   bool is_static = false;
1707 
1708   if (method->is_static()) {
1709     klass_slot_offset = stack_slots;
1710     stack_slots += VMRegImpl::slots_per_word;
1711     klass_offset = klass_slot_offset * VMRegImpl::stack_slot_size;
1712     is_static = true;
1713   }
1714 
1715   // Plus a lock if needed
1716 
1717   if (method->is_synchronized()) {
1718     lock_slot_offset = stack_slots;
1719     stack_slots += VMRegImpl::slots_per_word;
1720   }
1721 
1722   // Now a place (+2) to save return values or temp during shuffling
1723   // + 2 for return address (which we own) and saved rbp,
1724   stack_slots += 4;
1725 
1726   // Ok The space we have allocated will look like:
1727   //
1728   //
1729   // FP-> |                     |
1730   //      |---------------------|
1731   //      | 2 slots for moves   |
1732   //      |---------------------|
1733   //      | lock box (if sync)  |
1734   //      |---------------------| <- lock_slot_offset  (-lock_slot_rbp_offset)
1735   //      | klass (if static)   |
1736   //      |---------------------| <- klass_slot_offset
1737   //      | oopHandle area      |
1738   //      |---------------------| <- oop_handle_offset (a max of 2 registers)
1739   //      | outbound memory     |
1740   //      | based arguments     |
1741   //      |                     |
1742   //      |---------------------|
1743   //      |                     |
1744   // SP-> | out_preserved_slots |
1745   //
1746   //
1747   // ****************************************************************************
1748   // WARNING - on Windows Java Natives use pascal calling convention and pop the
1749   // arguments off of the stack after the jni call. Before the call we can use
1750   // instructions that are SP relative. After the jni call we switch to FP
1751   // relative instructions instead of re-adjusting the stack on windows.
1752   // ****************************************************************************
1753 
1754 
1755   // Now compute actual number of stack words we need rounding to make
1756   // stack properly aligned.
1757   stack_slots = round_to(stack_slots, StackAlignmentInSlots);
1758 
1759   int stack_size = stack_slots * VMRegImpl::stack_slot_size;
1760 
1761   intptr_t start = (intptr_t)__ pc();
1762 
1763   // First thing make an ic check to see if we should even be here
1764 
1765   // We are free to use all registers as temps without saving them and
1766   // restoring them except rbp. rbp is the only callee save register
1767   // as far as the interpreter and the compiler(s) are concerned.
1768 
1769 
1770   const Register ic_reg = rax;
1771   const Register receiver = rcx;
1772   Label hit;
1773   Label exception_pending;
1774 
1775   __ verify_oop(receiver);
1776   __ cmpptr(ic_reg, Address(receiver, oopDesc::klass_offset_in_bytes()));
1777   __ jcc(Assembler::equal, hit);
1778 
1779   __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
1780 
1781   // verified entry must be aligned for code patching.
1782   // and the first 5 bytes must be in the same cache line
1783   // if we align at 8 then we will be sure 5 bytes are in the same line
1784   __ align(8);
1785 
1786   __ bind(hit);
1787 
1788   int vep_offset = ((intptr_t)__ pc()) - start;
1789 
1790 #ifdef COMPILER1
1791   if (InlineObjectHash && method->intrinsic_id() == vmIntrinsics::_hashCode) {
1792     // Object.hashCode can pull the hashCode from the header word
1793     // instead of doing a full VM transition once it's been computed.
1794     // Since hashCode is usually polymorphic at call sites we can't do
1795     // this optimization at the call site without a lot of work.
1796     Label slowCase;
1797     Register receiver = rcx;
1798     Register result = rax;
1799     __ movptr(result, Address(receiver, oopDesc::mark_offset_in_bytes()));
1800 
1801     // check if locked
1802     __ testptr(result, markOopDesc::unlocked_value);
1803     __ jcc (Assembler::zero, slowCase);
1804 
1805     if (UseBiasedLocking) {
1806       // Check if biased and fall through to runtime if so
1807       __ testptr(result, markOopDesc::biased_lock_bit_in_place);
1808       __ jcc (Assembler::notZero, slowCase);
1809     }
1810 
1811     // get hash
1812     __ andptr(result, markOopDesc::hash_mask_in_place);
1813     // test if hashCode exists
1814     __ jcc  (Assembler::zero, slowCase);
1815     __ shrptr(result, markOopDesc::hash_shift);
1816     __ ret(0);
1817     __ bind (slowCase);
1818   }
1819 #endif // COMPILER1
1820 
1821   // The instruction at the verified entry point must be 5 bytes or longer
1822   // because it can be patched on the fly by make_non_entrant. The stack bang
1823   // instruction fits that requirement.
1824 
1825   // Generate stack overflow check
1826 
1827   if (UseStackBanging) {
1828     __ bang_stack_with_offset(StackShadowPages*os::vm_page_size());
1829   } else {
1830     // need a 5 byte instruction to allow MT safe patching to non-entrant
1831     __ fat_nop();
1832   }
1833 
1834   // Generate a new frame for the wrapper.
1835   __ enter();
1836   // -2 because return address is already present and so is saved rbp
1837   __ subptr(rsp, stack_size - 2*wordSize);
1838 
1839   // Frame is now completed as far as size and linkage.
1840   int frame_complete = ((intptr_t)__ pc()) - start;
1841 
1842   if (UseRTMLocking) {
1843     // Abort RTM transaction before calling JNI
1844     // because critical section will be large and will be
1845     // aborted anyway. Also nmethod could be deoptimized.
1846     __ xabort(0);
1847   }
1848 
1849   // Calculate the difference between rsp and rbp,. We need to know it
1850   // after the native call because on windows Java Natives will pop
1851   // the arguments and it is painful to do rsp relative addressing
1852   // in a platform independent way. So after the call we switch to
1853   // rbp, relative addressing.
1854 
1855   int fp_adjustment = stack_size - 2*wordSize;
1856 
1857 #ifdef COMPILER2
1858   // C2 may leave the stack dirty if not in SSE2+ mode
1859   if (UseSSE >= 2) {
1860     __ verify_FPU(0, "c2i transition should have clean FPU stack");
1861   } else {
1862     __ empty_FPU_stack();
1863   }
1864 #endif /* COMPILER2 */
1865 
1866   // Compute the rbp, offset for any slots used after the jni call
1867 
1868   int lock_slot_rbp_offset = (lock_slot_offset*VMRegImpl::stack_slot_size) - fp_adjustment;
1869 
1870   // We use rdi as a thread pointer because it is callee save and
1871   // if we load it once it is usable thru the entire wrapper
1872   const Register thread = rdi;
1873 
1874   // We use rsi as the oop handle for the receiver/klass
1875   // It is callee save so it survives the call to native
1876 
1877   const Register oop_handle_reg = rsi;
1878 
1879   __ get_thread(thread);
1880 
1881   if (is_critical_native) {
1882     check_needs_gc_for_critical_native(masm, thread, stack_slots, total_c_args, total_in_args,
1883                                        oop_handle_offset, oop_maps, in_regs, in_sig_bt);
1884   }
1885 
1886   //
1887   // We immediately shuffle the arguments so that any vm call we have to
1888   // make from here on out (sync slow path, jvmti, etc.) we will have
1889   // captured the oops from our caller and have a valid oopMap for
1890   // them.
1891 
1892   // -----------------
1893   // The Grand Shuffle
1894   //
1895   // Natives require 1 or 2 extra arguments over the normal ones: the JNIEnv*
1896   // and, if static, the class mirror instead of a receiver.  This pretty much
1897   // guarantees that register layout will not match (and x86 doesn't use reg
1898   // parms though amd does).  Since the native abi doesn't use register args
1899   // and the java conventions does we don't have to worry about collisions.
1900   // All of our moved are reg->stack or stack->stack.
1901   // We ignore the extra arguments during the shuffle and handle them at the
1902   // last moment. The shuffle is described by the two calling convention
1903   // vectors we have in our possession. We simply walk the java vector to
1904   // get the source locations and the c vector to get the destinations.
1905 
1906   int c_arg = is_critical_native ? 0 : (method->is_static() ? 2 : 1 );
1907 
1908   // Record rsp-based slot for receiver on stack for non-static methods
1909   int receiver_offset = -1;
1910 
1911   // This is a trick. We double the stack slots so we can claim
1912   // the oops in the caller's frame. Since we are sure to have
1913   // more args than the caller doubling is enough to make
1914   // sure we can capture all the incoming oop args from the
1915   // caller.
1916   //
1917   OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1918 
1919   // Mark location of rbp,
1920   // map->set_callee_saved(VMRegImpl::stack2reg( stack_slots - 2), stack_slots * 2, 0, rbp->as_VMReg());
1921 
1922   // We know that we only have args in at most two integer registers (rcx, rdx). So rax, rbx
1923   // Are free to temporaries if we have to do  stack to steck moves.
1924   // All inbound args are referenced based on rbp, and all outbound args via rsp.
1925 
1926   for (int i = 0; i < total_in_args ; i++, c_arg++ ) {
1927     switch (in_sig_bt[i]) {
1928       case T_ARRAY:
1929         if (is_critical_native) {
1930           unpack_array_argument(masm, in_regs[i], in_elem_bt[i], out_regs[c_arg + 1], out_regs[c_arg]);
1931           c_arg++;
1932           break;
1933         }
1934       case T_OBJECT:
1935         assert(!is_critical_native, "no oop arguments");
1936         object_move(masm, map, oop_handle_offset, stack_slots, in_regs[i], out_regs[c_arg],
1937                     ((i == 0) && (!is_static)),
1938                     &receiver_offset);
1939         break;
1940       case T_VOID:
1941         break;
1942 
1943       case T_FLOAT:
1944         float_move(masm, in_regs[i], out_regs[c_arg]);
1945           break;
1946 
1947       case T_DOUBLE:
1948         assert( i + 1 < total_in_args &&
1949                 in_sig_bt[i + 1] == T_VOID &&
1950                 out_sig_bt[c_arg+1] == T_VOID, "bad arg list");
1951         double_move(masm, in_regs[i], out_regs[c_arg]);
1952         break;
1953 
1954       case T_LONG :
1955         long_move(masm, in_regs[i], out_regs[c_arg]);
1956         break;
1957 
1958       case T_ADDRESS: assert(false, "found T_ADDRESS in java args");
1959 
1960       default:
1961         simple_move32(masm, in_regs[i], out_regs[c_arg]);
1962     }
1963   }
1964 
1965   // Pre-load a static method's oop into rsi.  Used both by locking code and
1966   // the normal JNI call code.
1967   if (method->is_static() && !is_critical_native) {
1968 
1969     //  load opp into a register
1970     __ movoop(oop_handle_reg, JNIHandles::make_local(method->method_holder()->java_mirror()));
1971 
1972     // Now handlize the static class mirror it's known not-null.
1973     __ movptr(Address(rsp, klass_offset), oop_handle_reg);
1974     map->set_oop(VMRegImpl::stack2reg(klass_slot_offset));
1975 
1976     // Now get the handle
1977     __ lea(oop_handle_reg, Address(rsp, klass_offset));
1978     // store the klass handle as second argument
1979     __ movptr(Address(rsp, wordSize), oop_handle_reg);
1980   }
1981 
1982   // Change state to native (we save the return address in the thread, since it might not
1983   // be pushed on the stack when we do a a stack traversal). It is enough that the pc()
1984   // points into the right code segment. It does not have to be the correct return pc.
1985   // We use the same pc/oopMap repeatedly when we call out
1986 
1987   intptr_t the_pc = (intptr_t) __ pc();
1988   oop_maps->add_gc_map(the_pc - start, map);
1989 
1990   __ set_last_Java_frame(thread, rsp, noreg, (address)the_pc);
1991 
1992 
1993   // We have all of the arguments setup at this point. We must not touch any register
1994   // argument registers at this point (what if we save/restore them there are no oop?
1995 
1996   {
1997     SkipIfEqual skip_if(masm, &DTraceMethodProbes, 0);
1998     __ mov_metadata(rax, method());
1999     __ call_VM_leaf(
2000          CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry),
2001          thread, rax);
2002   }
2003 
2004   // RedefineClasses() tracing support for obsolete method entry
2005   if (RC_TRACE_IN_RANGE(0x00001000, 0x00002000)) {
2006     __ mov_metadata(rax, method());
2007     __ call_VM_leaf(
2008          CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
2009          thread, rax);
2010   }
2011 
2012   // These are register definitions we need for locking/unlocking
2013   const Register swap_reg = rax;  // Must use rax, for cmpxchg instruction
2014   const Register obj_reg  = rcx;  // Will contain the oop
2015   const Register lock_reg = rdx;  // Address of compiler lock object (BasicLock)
2016 
2017   Label slow_path_lock;
2018   Label lock_done;
2019 
2020   // Lock a synchronized method
2021   if (method->is_synchronized()) {
2022     assert(!is_critical_native, "unhandled");
2023 
2024 
2025     const int mark_word_offset = BasicLock::displaced_header_offset_in_bytes();
2026 
2027     // Get the handle (the 2nd argument)
2028     __ movptr(oop_handle_reg, Address(rsp, wordSize));
2029 
2030     // Get address of the box
2031 
2032     __ lea(lock_reg, Address(rbp, lock_slot_rbp_offset));
2033 
2034     // Load the oop from the handle
2035     __ movptr(obj_reg, Address(oop_handle_reg, 0));
2036 
2037     if (UseBiasedLocking) {
2038       // Note that oop_handle_reg is trashed during this call
2039       __ biased_locking_enter(lock_reg, obj_reg, swap_reg, oop_handle_reg, false, lock_done, &slow_path_lock);
2040     }
2041 
2042     // Load immediate 1 into swap_reg %rax,
2043     __ movptr(swap_reg, 1);
2044 
2045     // Load (object->mark() | 1) into swap_reg %rax,
2046     __ orptr(swap_reg, Address(obj_reg, 0));
2047 
2048     // Save (object->mark() | 1) into BasicLock's displaced header
2049     __ movptr(Address(lock_reg, mark_word_offset), swap_reg);
2050 
2051     if (os::is_MP()) {
2052       __ lock();
2053     }
2054 
2055     // src -> dest iff dest == rax, else rax, <- dest
2056     // *obj_reg = lock_reg iff *obj_reg == rax, else rax, = *(obj_reg)
2057     __ cmpxchgptr(lock_reg, Address(obj_reg, 0));
2058     __ jcc(Assembler::equal, lock_done);
2059 
2060     // Test if the oopMark is an obvious stack pointer, i.e.,
2061     //  1) (mark & 3) == 0, and
2062     //  2) rsp <= mark < mark + os::pagesize()
2063     // These 3 tests can be done by evaluating the following
2064     // expression: ((mark - rsp) & (3 - os::vm_page_size())),
2065     // assuming both stack pointer and pagesize have their
2066     // least significant 2 bits clear.
2067     // NOTE: the oopMark is in swap_reg %rax, as the result of cmpxchg
2068 
2069     __ subptr(swap_reg, rsp);
2070     __ andptr(swap_reg, 3 - os::vm_page_size());
2071 
2072     // Save the test result, for recursive case, the result is zero
2073     __ movptr(Address(lock_reg, mark_word_offset), swap_reg);
2074     __ jcc(Assembler::notEqual, slow_path_lock);
2075     // Slow path will re-enter here
2076     __ bind(lock_done);
2077 
2078     if (UseBiasedLocking) {
2079       // Re-fetch oop_handle_reg as we trashed it above
2080       __ movptr(oop_handle_reg, Address(rsp, wordSize));
2081     }
2082   }
2083 
2084 
2085   // Finally just about ready to make the JNI call
2086 
2087 
2088   // get JNIEnv* which is first argument to native
2089   if (!is_critical_native) {
2090     __ lea(rdx, Address(thread, in_bytes(JavaThread::jni_environment_offset())));
2091     __ movptr(Address(rsp, 0), rdx);
2092   }
2093 
2094   // Now set thread in native
2095   __ movl(Address(thread, JavaThread::thread_state_offset()), _thread_in_native);
2096 
2097   __ call(RuntimeAddress(native_func));
2098 
2099   // Verify or restore cpu control state after JNI call
2100   __ restore_cpu_control_state_after_jni();
2101 
2102   // WARNING - on Windows Java Natives use pascal calling convention and pop the
2103   // arguments off of the stack. We could just re-adjust the stack pointer here
2104   // and continue to do SP relative addressing but we instead switch to FP
2105   // relative addressing.
2106 
2107   // Unpack native results.
2108   switch (ret_type) {
2109   case T_BOOLEAN: __ c2bool(rax);            break;
2110   case T_CHAR   : __ andptr(rax, 0xFFFF);    break;
2111   case T_BYTE   : __ sign_extend_byte (rax); break;
2112   case T_SHORT  : __ sign_extend_short(rax); break;
2113   case T_INT    : /* nothing to do */        break;
2114   case T_DOUBLE :
2115   case T_FLOAT  :
2116     // Result is in st0 we'll save as needed
2117     break;
2118   case T_ARRAY:                 // Really a handle
2119   case T_OBJECT:                // Really a handle
2120       break; // can't de-handlize until after safepoint check
2121   case T_VOID: break;
2122   case T_LONG: break;
2123   default       : ShouldNotReachHere();
2124   }
2125 
2126   // Switch thread to "native transition" state before reading the synchronization state.
2127   // This additional state is necessary because reading and testing the synchronization
2128   // state is not atomic w.r.t. GC, as this scenario demonstrates:
2129   //     Java thread A, in _thread_in_native state, loads _not_synchronized and is preempted.
2130   //     VM thread changes sync state to synchronizing and suspends threads for GC.
2131   //     Thread A is resumed to finish this native method, but doesn't block here since it
2132   //     didn't see any synchronization is progress, and escapes.
2133   __ movl(Address(thread, JavaThread::thread_state_offset()), _thread_in_native_trans);
2134 
2135   if(os::is_MP()) {
2136     if (UseMembar) {
2137       // Force this write out before the read below
2138       __ membar(Assembler::Membar_mask_bits(
2139            Assembler::LoadLoad | Assembler::LoadStore |
2140            Assembler::StoreLoad | Assembler::StoreStore));
2141     } else {
2142       // Write serialization page so VM thread can do a pseudo remote membar.
2143       // We use the current thread pointer to calculate a thread specific
2144       // offset to write to within the page. This minimizes bus traffic
2145       // due to cache line collision.
2146       __ serialize_memory(thread, rcx);
2147     }
2148   }
2149 
2150   if (AlwaysRestoreFPU) {
2151     // Make sure the control word is correct.
2152     __ fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_std()));
2153   }
2154 
2155   Label after_transition;
2156 
2157   // check for safepoint operation in progress and/or pending suspend requests
2158   { Label Continue;
2159 
2160     __ cmp32(ExternalAddress((address)SafepointSynchronize::address_of_state()),
2161              SafepointSynchronize::_not_synchronized);
2162 
2163     Label L;
2164     __ jcc(Assembler::notEqual, L);
2165     __ cmpl(Address(thread, JavaThread::suspend_flags_offset()), 0);
2166     __ jcc(Assembler::equal, Continue);
2167     __ bind(L);
2168 
2169     // Don't use call_VM as it will see a possible pending exception and forward it
2170     // and never return here preventing us from clearing _last_native_pc down below.
2171     // Also can't use call_VM_leaf either as it will check to see if rsi & rdi are
2172     // preserved and correspond to the bcp/locals pointers. So we do a runtime call
2173     // by hand.
2174     //
2175     save_native_result(masm, ret_type, stack_slots);
2176     __ push(thread);
2177     if (!is_critical_native) {
2178       __ call(RuntimeAddress(CAST_FROM_FN_PTR(address,
2179                                               JavaThread::check_special_condition_for_native_trans)));
2180     } else {
2181       __ call(RuntimeAddress(CAST_FROM_FN_PTR(address,
2182                                               JavaThread::check_special_condition_for_native_trans_and_transition)));
2183     }
2184     __ increment(rsp, wordSize);
2185     // Restore any method result value
2186     restore_native_result(masm, ret_type, stack_slots);
2187 
2188     if (is_critical_native) {
2189       // The call above performed the transition to thread_in_Java so
2190       // skip the transition logic below.
2191       __ jmpb(after_transition);
2192     }
2193 
2194     __ bind(Continue);
2195   }
2196 
2197   // change thread state
2198   __ movl(Address(thread, JavaThread::thread_state_offset()), _thread_in_Java);
2199   __ bind(after_transition);
2200 
2201   Label reguard;
2202   Label reguard_done;
2203   __ cmpl(Address(thread, JavaThread::stack_guard_state_offset()), JavaThread::stack_guard_yellow_disabled);
2204   __ jcc(Assembler::equal, reguard);
2205 
2206   // slow path reguard  re-enters here
2207   __ bind(reguard_done);
2208 
2209   // Handle possible exception (will unlock if necessary)
2210 
2211   // native result if any is live
2212 
2213   // Unlock
2214   Label slow_path_unlock;
2215   Label unlock_done;
2216   if (method->is_synchronized()) {
2217 
2218     Label done;
2219 
2220     // Get locked oop from the handle we passed to jni
2221     __ movptr(obj_reg, Address(oop_handle_reg, 0));
2222 
2223     if (UseBiasedLocking) {
2224       __ biased_locking_exit(obj_reg, rbx, done);
2225     }
2226 
2227     // Simple recursive lock?
2228 
2229     __ cmpptr(Address(rbp, lock_slot_rbp_offset), (int32_t)NULL_WORD);
2230     __ jcc(Assembler::equal, done);
2231 
2232     // Must save rax, if if it is live now because cmpxchg must use it
2233     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
2234       save_native_result(masm, ret_type, stack_slots);
2235     }
2236 
2237     //  get old displaced header
2238     __ movptr(rbx, Address(rbp, lock_slot_rbp_offset));
2239 
2240     // get address of the stack lock
2241     __ lea(rax, Address(rbp, lock_slot_rbp_offset));
2242 
2243     // Atomic swap old header if oop still contains the stack lock
2244     if (os::is_MP()) {
2245     __ lock();
2246     }
2247 
2248     // src -> dest iff dest == rax, else rax, <- dest
2249     // *obj_reg = rbx, iff *obj_reg == rax, else rax, = *(obj_reg)
2250     __ cmpxchgptr(rbx, Address(obj_reg, 0));
2251     __ jcc(Assembler::notEqual, slow_path_unlock);
2252 
2253     // slow path re-enters here
2254     __ bind(unlock_done);
2255     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
2256       restore_native_result(masm, ret_type, stack_slots);
2257     }
2258 
2259     __ bind(done);
2260 
2261   }
2262 
2263   {
2264     SkipIfEqual skip_if(masm, &DTraceMethodProbes, 0);
2265     // Tell dtrace about this method exit
2266     save_native_result(masm, ret_type, stack_slots);
2267     __ mov_metadata(rax, method());
2268     __ call_VM_leaf(
2269          CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit),
2270          thread, rax);
2271     restore_native_result(masm, ret_type, stack_slots);
2272   }
2273 
2274   // We can finally stop using that last_Java_frame we setup ages ago
2275 
2276   __ reset_last_Java_frame(thread, false, true);
2277 
2278   // Unpack oop result
2279   if (ret_type == T_OBJECT || ret_type == T_ARRAY) {
2280       Label L;
2281       __ cmpptr(rax, (int32_t)NULL_WORD);
2282       __ jcc(Assembler::equal, L);
2283       __ movptr(rax, Address(rax, 0));
2284       __ bind(L);
2285       __ verify_oop(rax);
2286   }
2287 
2288   if (!is_critical_native) {
2289     // reset handle block
2290     __ movptr(rcx, Address(thread, JavaThread::active_handles_offset()));
2291     __ movl(Address(rcx, JNIHandleBlock::top_offset_in_bytes()), NULL_WORD);
2292 
2293     // Any exception pending?
2294     __ cmpptr(Address(thread, in_bytes(Thread::pending_exception_offset())), (int32_t)NULL_WORD);
2295     __ jcc(Assembler::notEqual, exception_pending);
2296   }
2297 
2298   // no exception, we're almost done
2299 
2300   // check that only result value is on FPU stack
2301   __ verify_FPU(ret_type == T_FLOAT || ret_type == T_DOUBLE ? 1 : 0, "native_wrapper normal exit");
2302 
2303   // Fixup floating pointer results so that result looks like a return from a compiled method
2304   if (ret_type == T_FLOAT) {
2305     if (UseSSE >= 1) {
2306       // Pop st0 and store as float and reload into xmm register
2307       __ fstp_s(Address(rbp, -4));
2308       __ movflt(xmm0, Address(rbp, -4));
2309     }
2310   } else if (ret_type == T_DOUBLE) {
2311     if (UseSSE >= 2) {
2312       // Pop st0 and store as double and reload into xmm register
2313       __ fstp_d(Address(rbp, -8));
2314       __ movdbl(xmm0, Address(rbp, -8));
2315     }
2316   }
2317 
2318   // Return
2319 
2320   __ leave();
2321   __ ret(0);
2322 
2323   // Unexpected paths are out of line and go here
2324 
2325   // Slow path locking & unlocking
2326   if (method->is_synchronized()) {
2327 
2328     // BEGIN Slow path lock
2329 
2330     __ bind(slow_path_lock);
2331 
2332     // has last_Java_frame setup. No exceptions so do vanilla call not call_VM
2333     // args are (oop obj, BasicLock* lock, JavaThread* thread)
2334     __ push(thread);
2335     __ push(lock_reg);
2336     __ push(obj_reg);
2337     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_locking_C)));
2338     __ addptr(rsp, 3*wordSize);
2339 
2340 #ifdef ASSERT
2341     { Label L;
2342     __ cmpptr(Address(thread, in_bytes(Thread::pending_exception_offset())), (int)NULL_WORD);
2343     __ jcc(Assembler::equal, L);
2344     __ stop("no pending exception allowed on exit from monitorenter");
2345     __ bind(L);
2346     }
2347 #endif
2348     __ jmp(lock_done);
2349 
2350     // END Slow path lock
2351 
2352     // BEGIN Slow path unlock
2353     __ bind(slow_path_unlock);
2354 
2355     // Slow path unlock
2356 
2357     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2358       save_native_result(masm, ret_type, stack_slots);
2359     }
2360     // Save pending exception around call to VM (which contains an EXCEPTION_MARK)
2361 
2362     __ pushptr(Address(thread, in_bytes(Thread::pending_exception_offset())));
2363     __ movptr(Address(thread, in_bytes(Thread::pending_exception_offset())), NULL_WORD);
2364 
2365 
2366     // should be a peal
2367     // +wordSize because of the push above
2368     // args are (oop obj, BasicLock* lock, JavaThread* thread)
2369     __ push(thread);
2370     __ lea(rax, Address(rbp, lock_slot_rbp_offset));
2371     __ push(rax);
2372 
2373     __ push(obj_reg);
2374     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C)));
2375     __ addptr(rsp, 3*wordSize);
2376 #ifdef ASSERT
2377     {
2378       Label L;
2379       __ cmpptr(Address(thread, in_bytes(Thread::pending_exception_offset())), (int32_t)NULL_WORD);
2380       __ jcc(Assembler::equal, L);
2381       __ stop("no pending exception allowed on exit complete_monitor_unlocking_C");
2382       __ bind(L);
2383     }
2384 #endif /* ASSERT */
2385 
2386     __ popptr(Address(thread, in_bytes(Thread::pending_exception_offset())));
2387 
2388     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2389       restore_native_result(masm, ret_type, stack_slots);
2390     }
2391     __ jmp(unlock_done);
2392     // END Slow path unlock
2393 
2394   }
2395 
2396   // SLOW PATH Reguard the stack if needed
2397 
2398   __ bind(reguard);
2399   save_native_result(masm, ret_type, stack_slots);
2400   {
2401     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages)));
2402   }
2403   restore_native_result(masm, ret_type, stack_slots);
2404   __ jmp(reguard_done);
2405 
2406 
2407   // BEGIN EXCEPTION PROCESSING
2408 
2409   if (!is_critical_native) {
2410     // Forward  the exception
2411     __ bind(exception_pending);
2412 
2413     // remove possible return value from FPU register stack
2414     __ empty_FPU_stack();
2415 
2416     // pop our frame
2417     __ leave();
2418     // and forward the exception
2419     __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2420   }
2421 
2422   __ flush();
2423 
2424   nmethod *nm = nmethod::new_native_nmethod(method,
2425                                             compile_id,
2426                                             masm->code(),
2427                                             vep_offset,
2428                                             frame_complete,
2429                                             stack_slots / VMRegImpl::slots_per_word,
2430                                             (is_static ? in_ByteSize(klass_offset) : in_ByteSize(receiver_offset)),
2431                                             in_ByteSize(lock_slot_offset*VMRegImpl::stack_slot_size),
2432                                             oop_maps);
2433 
2434   if (is_critical_native) {
2435     nm->set_lazy_critical_native(true);
2436   }
2437 
2438   return nm;
2439 
2440 }
2441 
2442 // this function returns the adjust size (in number of words) to a c2i adapter
2443 // activation for use during deoptimization
2444 int Deoptimization::last_frame_adjust(int callee_parameters, int callee_locals ) {
2445   return (callee_locals - callee_parameters) * Interpreter::stackElementWords;
2446 }
2447 
2448 
2449 uint SharedRuntime::out_preserve_stack_slots() {
2450   return 0;
2451 }
2452 
2453 //------------------------------generate_deopt_blob----------------------------
2454 void SharedRuntime::generate_deopt_blob() {
2455   // allocate space for the code
2456   ResourceMark rm;
2457   // setup code generation tools
2458   // note: the buffer code size must account for StackShadowPages=50
2459   CodeBuffer   buffer("deopt_blob", 1536, 1024);
2460   MacroAssembler* masm = new MacroAssembler(&buffer);
2461   int frame_size_in_words;
2462   OopMap* map = NULL;
2463   // Account for the extra args we place on the stack
2464   // by the time we call fetch_unroll_info
2465   const int additional_words = 2; // deopt kind, thread
2466 
2467   OopMapSet *oop_maps = new OopMapSet();
2468 
2469   // -------------
2470   // This code enters when returning to a de-optimized nmethod.  A return
2471   // address has been pushed on the the stack, and return values are in
2472   // registers.
2473   // If we are doing a normal deopt then we were called from the patched
2474   // nmethod from the point we returned to the nmethod. So the return
2475   // address on the stack is wrong by NativeCall::instruction_size
2476   // We will adjust the value to it looks like we have the original return
2477   // address on the stack (like when we eagerly deoptimized).
2478   // In the case of an exception pending with deoptimized then we enter
2479   // with a return address on the stack that points after the call we patched
2480   // into the exception handler. We have the following register state:
2481   //    rax,: exception
2482   //    rbx,: exception handler
2483   //    rdx: throwing pc
2484   // So in this case we simply jam rdx into the useless return address and
2485   // the stack looks just like we want.
2486   //
2487   // At this point we need to de-opt.  We save the argument return
2488   // registers.  We call the first C routine, fetch_unroll_info().  This
2489   // routine captures the return values and returns a structure which
2490   // describes the current frame size and the sizes of all replacement frames.
2491   // The current frame is compiled code and may contain many inlined
2492   // functions, each with their own JVM state.  We pop the current frame, then
2493   // push all the new frames.  Then we call the C routine unpack_frames() to
2494   // populate these frames.  Finally unpack_frames() returns us the new target
2495   // address.  Notice that callee-save registers are BLOWN here; they have
2496   // already been captured in the vframeArray at the time the return PC was
2497   // patched.
2498   address start = __ pc();
2499   Label cont;
2500 
2501   // Prolog for non exception case!
2502 
2503   // Save everything in sight.
2504 
2505   map = RegisterSaver::save_live_registers(masm, additional_words, &frame_size_in_words, false);
2506   // Normal deoptimization
2507   __ push(Deoptimization::Unpack_deopt);
2508   __ jmp(cont);
2509 
2510   int reexecute_offset = __ pc() - start;
2511 
2512   // Reexecute case
2513   // return address is the pc describes what bci to do re-execute at
2514 
2515   // No need to update map as each call to save_live_registers will produce identical oopmap
2516   (void) RegisterSaver::save_live_registers(masm, additional_words, &frame_size_in_words, false);
2517 
2518   __ push(Deoptimization::Unpack_reexecute);
2519   __ jmp(cont);
2520 
2521   int exception_offset = __ pc() - start;
2522 
2523   // Prolog for exception case
2524 
2525   // all registers are dead at this entry point, except for rax, and
2526   // rdx which contain the exception oop and exception pc
2527   // respectively.  Set them in TLS and fall thru to the
2528   // unpack_with_exception_in_tls entry point.
2529 
2530   __ get_thread(rdi);
2531   __ movptr(Address(rdi, JavaThread::exception_pc_offset()), rdx);
2532   __ movptr(Address(rdi, JavaThread::exception_oop_offset()), rax);
2533 
2534   int exception_in_tls_offset = __ pc() - start;
2535 
2536   // new implementation because exception oop is now passed in JavaThread
2537 
2538   // Prolog for exception case
2539   // All registers must be preserved because they might be used by LinearScan
2540   // Exceptiop oop and throwing PC are passed in JavaThread
2541   // tos: stack at point of call to method that threw the exception (i.e. only
2542   // args are on the stack, no return address)
2543 
2544   // make room on stack for the return address
2545   // It will be patched later with the throwing pc. The correct value is not
2546   // available now because loading it from memory would destroy registers.
2547   __ push(0);
2548 
2549   // Save everything in sight.
2550 
2551   // No need to update map as each call to save_live_registers will produce identical oopmap
2552   (void) RegisterSaver::save_live_registers(masm, additional_words, &frame_size_in_words, false);
2553 
2554   // Now it is safe to overwrite any register
2555 
2556   // store the correct deoptimization type
2557   __ push(Deoptimization::Unpack_exception);
2558 
2559   // load throwing pc from JavaThread and patch it as the return address
2560   // of the current frame. Then clear the field in JavaThread
2561   __ get_thread(rdi);
2562   __ movptr(rdx, Address(rdi, JavaThread::exception_pc_offset()));
2563   __ movptr(Address(rbp, wordSize), rdx);
2564   __ movptr(Address(rdi, JavaThread::exception_pc_offset()), NULL_WORD);
2565 
2566 #ifdef ASSERT
2567   // verify that there is really an exception oop in JavaThread
2568   __ movptr(rax, Address(rdi, JavaThread::exception_oop_offset()));
2569   __ verify_oop(rax);
2570 
2571   // verify that there is no pending exception
2572   Label no_pending_exception;
2573   __ movptr(rax, Address(rdi, Thread::pending_exception_offset()));
2574   __ testptr(rax, rax);
2575   __ jcc(Assembler::zero, no_pending_exception);
2576   __ stop("must not have pending exception here");
2577   __ bind(no_pending_exception);
2578 #endif
2579 
2580   __ bind(cont);
2581 
2582   // Compiled code leaves the floating point stack dirty, empty it.
2583   __ empty_FPU_stack();
2584 
2585 
2586   // Call C code.  Need thread and this frame, but NOT official VM entry
2587   // crud.  We cannot block on this call, no GC can happen.
2588   __ get_thread(rcx);
2589   __ push(rcx);
2590   // fetch_unroll_info needs to call last_java_frame()
2591   __ set_last_Java_frame(rcx, noreg, noreg, NULL);
2592 
2593   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::fetch_unroll_info)));
2594 
2595   // Need to have an oopmap that tells fetch_unroll_info where to
2596   // find any register it might need.
2597 
2598   oop_maps->add_gc_map( __ pc()-start, map);
2599 
2600   // Discard arg to fetch_unroll_info
2601   __ pop(rcx);
2602 
2603   __ get_thread(rcx);
2604   __ reset_last_Java_frame(rcx, false, false);
2605 
2606   // Load UnrollBlock into EDI
2607   __ mov(rdi, rax);
2608 
2609   // Move the unpack kind to a safe place in the UnrollBlock because
2610   // we are very short of registers
2611 
2612   Address unpack_kind(rdi, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes());
2613   // retrieve the deopt kind from where we left it.
2614   __ pop(rax);
2615   __ movl(unpack_kind, rax);                      // save the unpack_kind value
2616 
2617    Label noException;
2618   __ cmpl(rax, Deoptimization::Unpack_exception);   // Was exception pending?
2619   __ jcc(Assembler::notEqual, noException);
2620   __ movptr(rax, Address(rcx, JavaThread::exception_oop_offset()));
2621   __ movptr(rdx, Address(rcx, JavaThread::exception_pc_offset()));
2622   __ movptr(Address(rcx, JavaThread::exception_oop_offset()), NULL_WORD);
2623   __ movptr(Address(rcx, JavaThread::exception_pc_offset()), NULL_WORD);
2624 
2625   __ verify_oop(rax);
2626 
2627   // Overwrite the result registers with the exception results.
2628   __ movptr(Address(rsp, RegisterSaver::raxOffset()*wordSize), rax);
2629   __ movptr(Address(rsp, RegisterSaver::rdxOffset()*wordSize), rdx);
2630 
2631   __ bind(noException);
2632 
2633   // Stack is back to only having register save data on the stack.
2634   // Now restore the result registers. Everything else is either dead or captured
2635   // in the vframeArray.
2636 
2637   RegisterSaver::restore_result_registers(masm);
2638 
2639   // Non standard control word may be leaked out through a safepoint blob, and we can
2640   // deopt at a poll point with the non standard control word. However, we should make
2641   // sure the control word is correct after restore_result_registers.
2642   __ fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_std()));
2643 
2644   // All of the register save area has been popped of the stack. Only the
2645   // return address remains.
2646 
2647   // Pop all the frames we must move/replace.
2648   //
2649   // Frame picture (youngest to oldest)
2650   // 1: self-frame (no frame link)
2651   // 2: deopting frame  (no frame link)
2652   // 3: caller of deopting frame (could be compiled/interpreted).
2653   //
2654   // Note: by leaving the return address of self-frame on the stack
2655   // and using the size of frame 2 to adjust the stack
2656   // when we are done the return to frame 3 will still be on the stack.
2657 
2658   // Pop deoptimized frame
2659   __ addptr(rsp, Address(rdi,Deoptimization::UnrollBlock::size_of_deoptimized_frame_offset_in_bytes()));
2660 
2661   // sp should be pointing at the return address to the caller (3)
2662 
2663   // Pick up the initial fp we should save
2664   // restore rbp before stack bang because if stack overflow is thrown it needs to be pushed (and preserved)
2665   __ movptr(rbp, Address(rdi, Deoptimization::UnrollBlock::initial_info_offset_in_bytes()));
2666 
2667 #ifdef ASSERT
2668   // Compilers generate code that bang the stack by as much as the
2669   // interpreter would need. So this stack banging should never
2670   // trigger a fault. Verify that it does not on non product builds.
2671   if (UseStackBanging) {
2672     __ movl(rbx, Address(rdi ,Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes()));
2673     __ bang_stack_size(rbx, rcx);
2674   }
2675 #endif
2676 
2677   // Load array of frame pcs into ECX
2678   __ movptr(rcx,Address(rdi,Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2679 
2680   __ pop(rsi); // trash the old pc
2681 
2682   // Load array of frame sizes into ESI
2683   __ movptr(rsi,Address(rdi,Deoptimization::UnrollBlock::frame_sizes_offset_in_bytes()));
2684 
2685   Address counter(rdi, Deoptimization::UnrollBlock::counter_temp_offset_in_bytes());
2686 
2687   __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock::number_of_frames_offset_in_bytes()));
2688   __ movl(counter, rbx);
2689 
2690   // Now adjust the caller's stack to make up for the extra locals
2691   // but record the original sp so that we can save it in the skeletal interpreter
2692   // frame and the stack walking of interpreter_sender will get the unextended sp
2693   // value and not the "real" sp value.
2694 
2695   Address sp_temp(rdi, Deoptimization::UnrollBlock::sender_sp_temp_offset_in_bytes());
2696   __ movptr(sp_temp, rsp);
2697   __ movl2ptr(rbx, Address(rdi, Deoptimization::UnrollBlock::caller_adjustment_offset_in_bytes()));
2698   __ subptr(rsp, rbx);
2699 
2700   // Push interpreter frames in a loop
2701   Label loop;
2702   __ bind(loop);
2703   __ movptr(rbx, Address(rsi, 0));      // Load frame size
2704 #ifdef CC_INTERP
2705   __ subptr(rbx, 4*wordSize);           // we'll push pc and ebp by hand and
2706 #ifdef ASSERT
2707   __ push(0xDEADDEAD);                  // Make a recognizable pattern
2708   __ push(0xDEADDEAD);
2709 #else /* ASSERT */
2710   __ subptr(rsp, 2*wordSize);           // skip the "static long no_param"
2711 #endif /* ASSERT */
2712 #else /* CC_INTERP */
2713   __ subptr(rbx, 2*wordSize);           // we'll push pc and rbp, by hand
2714 #endif /* CC_INTERP */
2715   __ pushptr(Address(rcx, 0));          // save return address
2716   __ enter();                           // save old & set new rbp,
2717   __ subptr(rsp, rbx);                  // Prolog!
2718   __ movptr(rbx, sp_temp);              // sender's sp
2719 #ifdef CC_INTERP
2720   __ movptr(Address(rbp,
2721                   -(sizeof(BytecodeInterpreter)) + in_bytes(byte_offset_of(BytecodeInterpreter, _sender_sp))),
2722           rbx); // Make it walkable
2723 #else /* CC_INTERP */
2724   // This value is corrected by layout_activation_impl
2725   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
2726   __ movptr(Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize), rbx); // Make it walkable
2727 #endif /* CC_INTERP */
2728   __ movptr(sp_temp, rsp);              // pass to next frame
2729   __ addptr(rsi, wordSize);             // Bump array pointer (sizes)
2730   __ addptr(rcx, wordSize);             // Bump array pointer (pcs)
2731   __ decrementl(counter);             // decrement counter
2732   __ jcc(Assembler::notZero, loop);
2733   __ pushptr(Address(rcx, 0));          // save final return address
2734 
2735   // Re-push self-frame
2736   __ enter();                           // save old & set new rbp,
2737 
2738   //  Return address and rbp, are in place
2739   // We'll push additional args later. Just allocate a full sized
2740   // register save area
2741   __ subptr(rsp, (frame_size_in_words-additional_words - 2) * wordSize);
2742 
2743   // Restore frame locals after moving the frame
2744   __ movptr(Address(rsp, RegisterSaver::raxOffset()*wordSize), rax);
2745   __ movptr(Address(rsp, RegisterSaver::rdxOffset()*wordSize), rdx);
2746   __ fstp_d(Address(rsp, RegisterSaver::fpResultOffset()*wordSize));   // Pop float stack and store in local
2747   if( UseSSE>=2 ) __ movdbl(Address(rsp, RegisterSaver::xmm0Offset()*wordSize), xmm0);
2748   if( UseSSE==1 ) __ movflt(Address(rsp, RegisterSaver::xmm0Offset()*wordSize), xmm0);
2749 
2750   // Set up the args to unpack_frame
2751 
2752   __ pushl(unpack_kind);                     // get the unpack_kind value
2753   __ get_thread(rcx);
2754   __ push(rcx);
2755 
2756   // set last_Java_sp, last_Java_fp
2757   __ set_last_Java_frame(rcx, noreg, rbp, NULL);
2758 
2759   // Call C code.  Need thread but NOT official VM entry
2760   // crud.  We cannot block on this call, no GC can happen.  Call should
2761   // restore return values to their stack-slots with the new SP.
2762   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2763   // Set an oopmap for the call site
2764   oop_maps->add_gc_map( __ pc()-start, new OopMap( frame_size_in_words, 0 ));
2765 
2766   // rax, contains the return result type
2767   __ push(rax);
2768 
2769   __ get_thread(rcx);
2770   __ reset_last_Java_frame(rcx, false, false);
2771 
2772   // Collect return values
2773   __ movptr(rax,Address(rsp, (RegisterSaver::raxOffset() + additional_words + 1)*wordSize));
2774   __ movptr(rdx,Address(rsp, (RegisterSaver::rdxOffset() + additional_words + 1)*wordSize));
2775 
2776   // Clear floating point stack before returning to interpreter
2777   __ empty_FPU_stack();
2778 
2779   // Check if we should push the float or double return value.
2780   Label results_done, yes_double_value;
2781   __ cmpl(Address(rsp, 0), T_DOUBLE);
2782   __ jcc (Assembler::zero, yes_double_value);
2783   __ cmpl(Address(rsp, 0), T_FLOAT);
2784   __ jcc (Assembler::notZero, results_done);
2785 
2786   // return float value as expected by interpreter
2787   if( UseSSE>=1 ) __ movflt(xmm0, Address(rsp, (RegisterSaver::xmm0Offset() + additional_words + 1)*wordSize));
2788   else            __ fld_d(Address(rsp, (RegisterSaver::fpResultOffset() + additional_words + 1)*wordSize));
2789   __ jmp(results_done);
2790 
2791   // return double value as expected by interpreter
2792   __ bind(yes_double_value);
2793   if( UseSSE>=2 ) __ movdbl(xmm0, Address(rsp, (RegisterSaver::xmm0Offset() + additional_words + 1)*wordSize));
2794   else            __ fld_d(Address(rsp, (RegisterSaver::fpResultOffset() + additional_words + 1)*wordSize));
2795 
2796   __ bind(results_done);
2797 
2798   // Pop self-frame.
2799   __ leave();                              // Epilog!
2800 
2801   // Jump to interpreter
2802   __ ret(0);
2803 
2804   // -------------
2805   // make sure all code is generated
2806   masm->flush();
2807 
2808   _deopt_blob = DeoptimizationBlob::create( &buffer, oop_maps, 0, exception_offset, reexecute_offset, frame_size_in_words);
2809   _deopt_blob->set_unpack_with_exception_in_tls_offset(exception_in_tls_offset);
2810 }
2811 
2812 
2813 #ifdef COMPILER2
2814 //------------------------------generate_uncommon_trap_blob--------------------
2815 void SharedRuntime::generate_uncommon_trap_blob() {
2816   // allocate space for the code
2817   ResourceMark rm;
2818   // setup code generation tools
2819   CodeBuffer   buffer("uncommon_trap_blob", 512, 512);
2820   MacroAssembler* masm = new MacroAssembler(&buffer);
2821 
2822   enum frame_layout {
2823     arg0_off,      // thread                     sp + 0 // Arg location for
2824     arg1_off,      // unloaded_class_index       sp + 1 // calling C
2825     // The frame sender code expects that rbp will be in the "natural" place and
2826     // will override any oopMap setting for it. We must therefore force the layout
2827     // so that it agrees with the frame sender code.
2828     rbp_off,       // callee saved register      sp + 2
2829     return_off,    // slot for return address    sp + 3
2830     framesize
2831   };
2832 
2833   address start = __ pc();
2834 
2835   if (UseRTMLocking) {
2836     // Abort RTM transaction before possible nmethod deoptimization.
2837     __ xabort(0);
2838   }
2839 
2840   // Push self-frame.
2841   __ subptr(rsp, return_off*wordSize);     // Epilog!
2842 
2843   // rbp, is an implicitly saved callee saved register (i.e. the calling
2844   // convention will save restore it in prolog/epilog) Other than that
2845   // there are no callee save registers no that adapter frames are gone.
2846   __ movptr(Address(rsp, rbp_off*wordSize), rbp);
2847 
2848   // Clear the floating point exception stack
2849   __ empty_FPU_stack();
2850 
2851   // set last_Java_sp
2852   __ get_thread(rdx);
2853   __ set_last_Java_frame(rdx, noreg, noreg, NULL);
2854 
2855   // Call C code.  Need thread but NOT official VM entry
2856   // crud.  We cannot block on this call, no GC can happen.  Call should
2857   // capture callee-saved registers as well as return values.
2858   __ movptr(Address(rsp, arg0_off*wordSize), rdx);
2859   // argument already in ECX
2860   __ movl(Address(rsp, arg1_off*wordSize),rcx);
2861   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::uncommon_trap)));
2862 
2863   // Set an oopmap for the call site
2864   OopMapSet *oop_maps = new OopMapSet();
2865   OopMap* map =  new OopMap( framesize, 0 );
2866   // No oopMap for rbp, it is known implicitly
2867 
2868   oop_maps->add_gc_map( __ pc()-start, map);
2869 
2870   __ get_thread(rcx);
2871 
2872   __ reset_last_Java_frame(rcx, false, false);
2873 
2874   // Load UnrollBlock into EDI
2875   __ movptr(rdi, rax);
2876 
2877   // Pop all the frames we must move/replace.
2878   //
2879   // Frame picture (youngest to oldest)
2880   // 1: self-frame (no frame link)
2881   // 2: deopting frame  (no frame link)
2882   // 3: caller of deopting frame (could be compiled/interpreted).
2883 
2884   // Pop self-frame.  We have no frame, and must rely only on EAX and ESP.
2885   __ addptr(rsp,(framesize-1)*wordSize);     // Epilog!
2886 
2887   // Pop deoptimized frame
2888   __ movl2ptr(rcx, Address(rdi,Deoptimization::UnrollBlock::size_of_deoptimized_frame_offset_in_bytes()));
2889   __ addptr(rsp, rcx);
2890 
2891   // sp should be pointing at the return address to the caller (3)
2892 
2893   // Pick up the initial fp we should save
2894   // restore rbp before stack bang because if stack overflow is thrown it needs to be pushed (and preserved)
2895   __ movptr(rbp, Address(rdi, Deoptimization::UnrollBlock::initial_info_offset_in_bytes()));
2896 
2897 #ifdef ASSERT
2898   // Compilers generate code that bang the stack by as much as the
2899   // interpreter would need. So this stack banging should never
2900   // trigger a fault. Verify that it does not on non product builds.
2901   if (UseStackBanging) {
2902     __ movl(rbx, Address(rdi ,Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes()));
2903     __ bang_stack_size(rbx, rcx);
2904   }
2905 #endif
2906 
2907   // Load array of frame pcs into ECX
2908   __ movl(rcx,Address(rdi,Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2909 
2910   __ pop(rsi); // trash the pc
2911 
2912   // Load array of frame sizes into ESI
2913   __ movptr(rsi,Address(rdi,Deoptimization::UnrollBlock::frame_sizes_offset_in_bytes()));
2914 
2915   Address counter(rdi, Deoptimization::UnrollBlock::counter_temp_offset_in_bytes());
2916 
2917   __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock::number_of_frames_offset_in_bytes()));
2918   __ movl(counter, rbx);
2919 
2920   // Now adjust the caller's stack to make up for the extra locals
2921   // but record the original sp so that we can save it in the skeletal interpreter
2922   // frame and the stack walking of interpreter_sender will get the unextended sp
2923   // value and not the "real" sp value.
2924 
2925   Address sp_temp(rdi, Deoptimization::UnrollBlock::sender_sp_temp_offset_in_bytes());
2926   __ movptr(sp_temp, rsp);
2927   __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock::caller_adjustment_offset_in_bytes()));
2928   __ subptr(rsp, rbx);
2929 
2930   // Push interpreter frames in a loop
2931   Label loop;
2932   __ bind(loop);
2933   __ movptr(rbx, Address(rsi, 0));      // Load frame size
2934 #ifdef CC_INTERP
2935   __ subptr(rbx, 4*wordSize);           // we'll push pc and ebp by hand and
2936 #ifdef ASSERT
2937   __ push(0xDEADDEAD);                  // Make a recognizable pattern
2938   __ push(0xDEADDEAD);                  // (parm to RecursiveInterpreter...)
2939 #else /* ASSERT */
2940   __ subptr(rsp, 2*wordSize);           // skip the "static long no_param"
2941 #endif /* ASSERT */
2942 #else /* CC_INTERP */
2943   __ subptr(rbx, 2*wordSize);           // we'll push pc and rbp, by hand
2944 #endif /* CC_INTERP */
2945   __ pushptr(Address(rcx, 0));          // save return address
2946   __ enter();                           // save old & set new rbp,
2947   __ subptr(rsp, rbx);                  // Prolog!
2948   __ movptr(rbx, sp_temp);              // sender's sp
2949 #ifdef CC_INTERP
2950   __ movptr(Address(rbp,
2951                   -(sizeof(BytecodeInterpreter)) + in_bytes(byte_offset_of(BytecodeInterpreter, _sender_sp))),
2952           rbx); // Make it walkable
2953 #else /* CC_INTERP */
2954   // This value is corrected by layout_activation_impl
2955   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD );
2956   __ movptr(Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize), rbx); // Make it walkable
2957 #endif /* CC_INTERP */
2958   __ movptr(sp_temp, rsp);              // pass to next frame
2959   __ addptr(rsi, wordSize);             // Bump array pointer (sizes)
2960   __ addptr(rcx, wordSize);             // Bump array pointer (pcs)
2961   __ decrementl(counter);             // decrement counter
2962   __ jcc(Assembler::notZero, loop);
2963   __ pushptr(Address(rcx, 0));            // save final return address
2964 
2965   // Re-push self-frame
2966   __ enter();                           // save old & set new rbp,
2967   __ subptr(rsp, (framesize-2) * wordSize);   // Prolog!
2968 
2969 
2970   // set last_Java_sp, last_Java_fp
2971   __ get_thread(rdi);
2972   __ set_last_Java_frame(rdi, noreg, rbp, NULL);
2973 
2974   // Call C code.  Need thread but NOT official VM entry
2975   // crud.  We cannot block on this call, no GC can happen.  Call should
2976   // restore return values to their stack-slots with the new SP.
2977   __ movptr(Address(rsp,arg0_off*wordSize),rdi);
2978   __ movl(Address(rsp,arg1_off*wordSize), Deoptimization::Unpack_uncommon_trap);
2979   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2980   // Set an oopmap for the call site
2981   oop_maps->add_gc_map( __ pc()-start, new OopMap( framesize, 0 ) );
2982 
2983   __ get_thread(rdi);
2984   __ reset_last_Java_frame(rdi, true, false);
2985 
2986   // Pop self-frame.
2987   __ leave();     // Epilog!
2988 
2989   // Jump to interpreter
2990   __ ret(0);
2991 
2992   // -------------
2993   // make sure all code is generated
2994   masm->flush();
2995 
2996    _uncommon_trap_blob = UncommonTrapBlob::create(&buffer, oop_maps, framesize);
2997 }
2998 #endif // COMPILER2
2999 
3000 //------------------------------generate_handler_blob------
3001 //
3002 // Generate a special Compile2Runtime blob that saves all registers,
3003 // setup oopmap, and calls safepoint code to stop the compiled code for
3004 // a safepoint.
3005 //
3006 SafepointBlob* SharedRuntime::generate_handler_blob(address call_ptr, int poll_type) {
3007 
3008   // Account for thread arg in our frame
3009   const int additional_words = 1;
3010   int frame_size_in_words;
3011 
3012   assert (StubRoutines::forward_exception_entry() != NULL, "must be generated before");
3013 
3014   ResourceMark rm;
3015   OopMapSet *oop_maps = new OopMapSet();
3016   OopMap* map;
3017 
3018   // allocate space for the code
3019   // setup code generation tools
3020   CodeBuffer   buffer("handler_blob", 1024, 512);
3021   MacroAssembler* masm = new MacroAssembler(&buffer);
3022 
3023   const Register java_thread = rdi; // callee-saved for VC++
3024   address start   = __ pc();
3025   address call_pc = NULL;
3026   bool cause_return = (poll_type == POLL_AT_RETURN);
3027   bool save_vectors = (poll_type == POLL_AT_VECTOR_LOOP);
3028 
3029   if (UseRTMLocking) {
3030     // Abort RTM transaction before calling runtime
3031     // because critical section will be large and will be
3032     // aborted anyway. Also nmethod could be deoptimized.
3033     __ xabort(0);
3034   }
3035 
3036   // If cause_return is true we are at a poll_return and there is
3037   // the return address on the stack to the caller on the nmethod
3038   // that is safepoint. We can leave this return on the stack and
3039   // effectively complete the return and safepoint in the caller.
3040   // Otherwise we push space for a return address that the safepoint
3041   // handler will install later to make the stack walking sensible.
3042   if (!cause_return)
3043     __ push(rbx);  // Make room for return address (or push it again)
3044 
3045   map = RegisterSaver::save_live_registers(masm, additional_words, &frame_size_in_words, false, save_vectors);
3046 
3047   // The following is basically a call_VM. However, we need the precise
3048   // address of the call in order to generate an oopmap. Hence, we do all the
3049   // work ourselves.
3050 
3051   // Push thread argument and setup last_Java_sp
3052   __ get_thread(java_thread);
3053   __ push(java_thread);
3054   __ set_last_Java_frame(java_thread, noreg, noreg, NULL);
3055 
3056   // if this was not a poll_return then we need to correct the return address now.
3057   if (!cause_return) {
3058     __ movptr(rax, Address(java_thread, JavaThread::saved_exception_pc_offset()));
3059     __ movptr(Address(rbp, wordSize), rax);
3060   }
3061 
3062   // do the call
3063   __ call(RuntimeAddress(call_ptr));
3064 
3065   // Set an oopmap for the call site.  This oopmap will map all
3066   // oop-registers and debug-info registers as callee-saved.  This
3067   // will allow deoptimization at this safepoint to find all possible
3068   // debug-info recordings, as well as let GC find all oops.
3069 
3070   oop_maps->add_gc_map( __ pc() - start, map);
3071 
3072   // Discard arg
3073   __ pop(rcx);
3074 
3075   Label noException;
3076 
3077   // Clear last_Java_sp again
3078   __ get_thread(java_thread);
3079   __ reset_last_Java_frame(java_thread, false, false);
3080 
3081   __ cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
3082   __ jcc(Assembler::equal, noException);
3083 
3084   // Exception pending
3085   RegisterSaver::restore_live_registers(masm, save_vectors);
3086 
3087   __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3088 
3089   __ bind(noException);
3090 
3091   // Normal exit, register restoring and exit
3092   RegisterSaver::restore_live_registers(masm, save_vectors);
3093 
3094   __ ret(0);
3095 
3096   // make sure all code is generated
3097   masm->flush();
3098 
3099   // Fill-out other meta info
3100   return SafepointBlob::create(&buffer, oop_maps, frame_size_in_words);
3101 }
3102 
3103 //
3104 // generate_resolve_blob - call resolution (static/virtual/opt-virtual/ic-miss
3105 //
3106 // Generate a stub that calls into vm to find out the proper destination
3107 // of a java call. All the argument registers are live at this point
3108 // but since this is generic code we don't know what they are and the caller
3109 // must do any gc of the args.
3110 //
3111 RuntimeStub* SharedRuntime::generate_resolve_blob(address destination, const char* name) {
3112   assert (StubRoutines::forward_exception_entry() != NULL, "must be generated before");
3113 
3114   // allocate space for the code
3115   ResourceMark rm;
3116 
3117   CodeBuffer buffer(name, 1000, 512);
3118   MacroAssembler* masm                = new MacroAssembler(&buffer);
3119 
3120   int frame_size_words;
3121   enum frame_layout {
3122                 thread_off,
3123                 extra_words };
3124 
3125   OopMapSet *oop_maps = new OopMapSet();
3126   OopMap* map = NULL;
3127 
3128   int start = __ offset();
3129 
3130   map = RegisterSaver::save_live_registers(masm, extra_words, &frame_size_words);
3131 
3132   int frame_complete = __ offset();
3133 
3134   const Register thread = rdi;
3135   __ get_thread(rdi);
3136 
3137   __ push(thread);
3138   __ set_last_Java_frame(thread, noreg, rbp, NULL);
3139 
3140   __ call(RuntimeAddress(destination));
3141 
3142 
3143   // Set an oopmap for the call site.
3144   // We need this not only for callee-saved registers, but also for volatile
3145   // registers that the compiler might be keeping live across a safepoint.
3146 
3147   oop_maps->add_gc_map( __ offset() - start, map);
3148 
3149   // rax, contains the address we are going to jump to assuming no exception got installed
3150 
3151   __ addptr(rsp, wordSize);
3152 
3153   // clear last_Java_sp
3154   __ reset_last_Java_frame(thread, true, false);
3155   // check for pending exceptions
3156   Label pending;
3157   __ cmpptr(Address(thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
3158   __ jcc(Assembler::notEqual, pending);
3159 
3160   // get the returned Method*
3161   __ get_vm_result_2(rbx, thread);
3162   __ movptr(Address(rsp, RegisterSaver::rbx_offset() * wordSize), rbx);
3163 
3164   __ movptr(Address(rsp, RegisterSaver::rax_offset() * wordSize), rax);
3165 
3166   RegisterSaver::restore_live_registers(masm);
3167 
3168   // We are back the the original state on entry and ready to go.
3169 
3170   __ jmp(rax);
3171 
3172   // Pending exception after the safepoint
3173 
3174   __ bind(pending);
3175 
3176   RegisterSaver::restore_live_registers(masm);
3177 
3178   // exception pending => remove activation and forward to exception handler
3179 
3180   __ get_thread(thread);
3181   __ movptr(Address(thread, JavaThread::vm_result_offset()), NULL_WORD);
3182   __ movptr(rax, Address(thread, Thread::pending_exception_offset()));
3183   __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3184 
3185   // -------------
3186   // make sure all code is generated
3187   masm->flush();
3188 
3189   // return the  blob
3190   // frame_size_words or bytes??
3191   return RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, frame_size_words, oop_maps, true);
3192 }