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