1 #ifdef USE_PRAGMA_IDENT_SRC
   2 #pragma ident "@(#)sharedRuntime_x86_64.cpp     1.44 07/09/17 09:26:01 JVM"
   3 #endif
   4 /*
   5  * Copyright 2003-2007 Sun Microsystems, Inc.  All Rights Reserved.
   6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   7  *
   8  * This code is free software; you can redistribute it and/or modify it
   9  * under the terms of the GNU General Public License version 2 only, as
  10  * published by the Free Software Foundation.
  11  *
  12  * This code is distributed in the hope that it will be useful, but WITHOUT
  13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  15  * version 2 for more details (a copy is included in the LICENSE file that
  16  * accompanied this code).
  17  *
  18  * You should have received a copy of the GNU General Public License version
  19  * 2 along with this work; if not, write to the Free Software Foundation,
  20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  21  *
  22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  23  * CA 95054 USA or visit www.sun.com if you need additional information or
  24  * have any questions.
  25  *  
  26  */
  27 
  28 #include "incls/_precompiled.incl"
  29 #include "incls/_sharedRuntime_x86_64.cpp.incl"
  30 
  31 DeoptimizationBlob *SharedRuntime::_deopt_blob;
  32 #ifdef COMPILER2
  33 UncommonTrapBlob   *SharedRuntime::_uncommon_trap_blob;
  34 ExceptionBlob      *OptoRuntime::_exception_blob;
  35 #endif // COMPILER2
  36 
  37 SafepointBlob      *SharedRuntime::_polling_page_safepoint_handler_blob;
  38 SafepointBlob      *SharedRuntime::_polling_page_return_handler_blob;
  39 RuntimeStub*       SharedRuntime::_wrong_method_blob;
  40 RuntimeStub*       SharedRuntime::_ic_miss_blob;
  41 RuntimeStub*       SharedRuntime::_resolve_opt_virtual_call_blob;
  42 RuntimeStub*       SharedRuntime::_resolve_virtual_call_blob;
  43 RuntimeStub*       SharedRuntime::_resolve_static_call_blob;
  44 
  45 #define __ masm->
  46 
  47 class SimpleRuntimeFrame {
  48 
  49   public:
  50 
  51   // Most of the runtime stubs have this simple frame layout.
  52   // This class exists to make the layout shared in one place.
  53   // Offsets are for compiler stack slots, which are jints.
  54   enum layout {
  55     // The frame sender code expects that rbp will be in the "natural" place and
  56     // will override any oopMap setting for it. We must therefore force the layout
  57     // so that it agrees with the frame sender code.
  58     rbp_off = frame::arg_reg_save_area_bytes/BytesPerInt,
  59     rbp_off2,
  60     return_off, return_off2,
  61     framesize 
  62   };
  63 };
  64 
  65 class RegisterSaver {
  66   // Capture info about frame layout.  Layout offsets are in jint
  67   // units because compiler frame slots are jints.
  68 #define DEF_XMM_OFFS(regnum) xmm ## regnum ## _off = xmm_off + (regnum)*16/BytesPerInt, xmm ## regnum ## H_off
  69   enum layout { 
  70     fpu_state_off = frame::arg_reg_save_area_bytes/BytesPerInt, // fxsave save area
  71     xmm_off       = fpu_state_off + 160/BytesPerInt,            // offset in fxsave save area
  72     DEF_XMM_OFFS(0),
  73     DEF_XMM_OFFS(1),
  74     DEF_XMM_OFFS(2),
  75     DEF_XMM_OFFS(3),
  76     DEF_XMM_OFFS(4),
  77     DEF_XMM_OFFS(5),
  78     DEF_XMM_OFFS(6),
  79     DEF_XMM_OFFS(7),
  80     DEF_XMM_OFFS(8),
  81     DEF_XMM_OFFS(9),
  82     DEF_XMM_OFFS(10),
  83     DEF_XMM_OFFS(11),
  84     DEF_XMM_OFFS(12),
  85     DEF_XMM_OFFS(13),
  86     DEF_XMM_OFFS(14),
  87     DEF_XMM_OFFS(15),
  88     fpu_state_end = fpu_state_off + ((FPUStateSizeInWords-1)*wordSize / BytesPerInt),
  89     fpu_stateH_end,
  90     r15_off, r15H_off,
  91     r14_off, r14H_off,
  92     r13_off, r13H_off,
  93     r12_off, r12H_off,
  94     r11_off, r11H_off,
  95     r10_off, r10H_off,
  96     r9_off,  r9H_off,
  97     r8_off,  r8H_off,
  98     rdi_off, rdiH_off,
  99     rsi_off, rsiH_off,
 100     ignore_off, ignoreH_off,  // extra copy of rbp
 101     rsp_off, rspH_off,
 102     rbx_off, rbxH_off,
 103     rdx_off, rdxH_off,
 104     rcx_off, rcxH_off,
 105     rax_off, raxH_off,
 106     // 16-byte stack alignment fill word: see MacroAssembler::push/pop_IU_state
 107     align_off, alignH_off,
 108     flags_off, flagsH_off,
 109     // The frame sender code expects that rbp will be in the "natural" place and
 110     // will override any oopMap setting for it. We must therefore force the layout
 111     // so that it agrees with the frame sender code.
 112     rbp_off, rbpH_off,        // copy of rbp we will restore
 113     return_off, returnH_off,  // slot for return address
 114     reg_save_size             // size in compiler stack slots
 115   };
 116 
 117  public: 
 118   static OopMap* save_live_registers(MacroAssembler* masm, int additional_frame_words, int* total_frame_words);
 119   static void restore_live_registers(MacroAssembler* masm);
 120 
 121   // Offsets into the register save area
 122   // Used by deoptimization when it is managing result register
 123   // values on its own
 124 
 125   static int rax_offset_in_bytes(void)    { return BytesPerInt * rax_off; }
 126   static int rbx_offset_in_bytes(void)    { return BytesPerInt * rbx_off; }
 127   static int xmm0_offset_in_bytes(void)   { return BytesPerInt * xmm0_off; }
 128   static int return_offset_in_bytes(void) { return BytesPerInt * return_off; }
 129 
 130   // During deoptimization only the result registers need to be restored,
 131   // all the other values have already been extracted.
 132   static void restore_result_registers(MacroAssembler* masm);
 133 };
 134 
 135 OopMap* RegisterSaver::save_live_registers(MacroAssembler* masm, int additional_frame_words, int* total_frame_words) {
 136 
 137   // Always make the frame size 16-byte aligned
 138   int frame_size_in_bytes = round_to(additional_frame_words*wordSize +
 139                                      reg_save_size*BytesPerInt, 16);
 140   // OopMap frame size is in compiler stack slots (jint's) not bytes or words
 141   int frame_size_in_slots = frame_size_in_bytes / BytesPerInt;
 142   // The caller will allocate additional_frame_words
 143   int additional_frame_slots = additional_frame_words*wordSize / BytesPerInt;
 144   // CodeBlob frame size is in words.
 145   int frame_size_in_words = frame_size_in_bytes / wordSize;
 146   *total_frame_words = frame_size_in_words;
 147 
 148   // Save registers, fpu state, and flags.
 149   // We assume caller has already pushed the return address onto the
 150   // stack, so rsp is 8-byte aligned here.
 151   // We push rpb twice in this sequence because we want the real rbp
 152   // to be under the return like a normal enter.
 153 
 154   __ enter();          // rsp becomes 16-byte aligned here
 155   __ push_CPU_state(); // Push a multiple of 16 bytes
 156   if (frame::arg_reg_save_area_bytes != 0) {
 157     // Allocate argument register save area
 158     __ subq(rsp, frame::arg_reg_save_area_bytes);
 159   }
 160 
 161   // Set an oopmap for the call site.  This oopmap will map all
 162   // oop-registers and debug-info registers as callee-saved.  This
 163   // will allow deoptimization at this safepoint to find all possible
 164   // debug-info recordings, as well as let GC find all oops.
 165 
 166   OopMapSet *oop_maps = new OopMapSet();
 167   OopMap* map = new OopMap(frame_size_in_slots, 0);
 168   map->set_callee_saved(VMRegImpl::stack2reg( rax_off  + additional_frame_slots), rax->as_VMReg());
 169   map->set_callee_saved(VMRegImpl::stack2reg( rcx_off  + additional_frame_slots), rcx->as_VMReg());
 170   map->set_callee_saved(VMRegImpl::stack2reg( rdx_off  + additional_frame_slots), rdx->as_VMReg());
 171   map->set_callee_saved(VMRegImpl::stack2reg( rbx_off  + additional_frame_slots), rbx->as_VMReg());
 172   // rbp location is known implicitly by the frame sender code, needs no oopmap
 173   // and the location where rbp was saved by is ignored
 174   map->set_callee_saved(VMRegImpl::stack2reg( rsi_off  + additional_frame_slots), rsi->as_VMReg());
 175   map->set_callee_saved(VMRegImpl::stack2reg( rdi_off  + additional_frame_slots), rdi->as_VMReg());
 176   map->set_callee_saved(VMRegImpl::stack2reg( r8_off   + additional_frame_slots), r8->as_VMReg());
 177   map->set_callee_saved(VMRegImpl::stack2reg( r9_off   + additional_frame_slots), r9->as_VMReg());
 178   map->set_callee_saved(VMRegImpl::stack2reg( r10_off  + additional_frame_slots), r10->as_VMReg());
 179   map->set_callee_saved(VMRegImpl::stack2reg( r11_off  + additional_frame_slots), r11->as_VMReg());
 180   map->set_callee_saved(VMRegImpl::stack2reg( r12_off  + additional_frame_slots), r12->as_VMReg());
 181   map->set_callee_saved(VMRegImpl::stack2reg( r13_off  + additional_frame_slots), r13->as_VMReg());
 182   map->set_callee_saved(VMRegImpl::stack2reg( r14_off  + additional_frame_slots), r14->as_VMReg());
 183   map->set_callee_saved(VMRegImpl::stack2reg( r15_off  + additional_frame_slots), r15->as_VMReg());
 184   map->set_callee_saved(VMRegImpl::stack2reg(xmm0_off  + additional_frame_slots), xmm0->as_VMReg());
 185   map->set_callee_saved(VMRegImpl::stack2reg(xmm1_off  + additional_frame_slots), xmm1->as_VMReg());
 186   map->set_callee_saved(VMRegImpl::stack2reg(xmm2_off  + additional_frame_slots), xmm2->as_VMReg());
 187   map->set_callee_saved(VMRegImpl::stack2reg(xmm3_off  + additional_frame_slots), xmm3->as_VMReg());
 188   map->set_callee_saved(VMRegImpl::stack2reg(xmm4_off  + additional_frame_slots), xmm4->as_VMReg());
 189   map->set_callee_saved(VMRegImpl::stack2reg(xmm5_off  + additional_frame_slots), xmm5->as_VMReg());
 190   map->set_callee_saved(VMRegImpl::stack2reg(xmm6_off  + additional_frame_slots), xmm6->as_VMReg());
 191   map->set_callee_saved(VMRegImpl::stack2reg(xmm7_off  + additional_frame_slots), xmm7->as_VMReg());
 192   map->set_callee_saved(VMRegImpl::stack2reg(xmm8_off  + additional_frame_slots), xmm8->as_VMReg());
 193   map->set_callee_saved(VMRegImpl::stack2reg(xmm9_off  + additional_frame_slots), xmm9->as_VMReg());
 194   map->set_callee_saved(VMRegImpl::stack2reg(xmm10_off + additional_frame_slots), xmm10->as_VMReg());
 195   map->set_callee_saved(VMRegImpl::stack2reg(xmm11_off + additional_frame_slots), xmm11->as_VMReg());
 196   map->set_callee_saved(VMRegImpl::stack2reg(xmm12_off + additional_frame_slots), xmm12->as_VMReg());
 197   map->set_callee_saved(VMRegImpl::stack2reg(xmm13_off + additional_frame_slots), xmm13->as_VMReg());
 198   map->set_callee_saved(VMRegImpl::stack2reg(xmm14_off + additional_frame_slots), xmm14->as_VMReg());
 199   map->set_callee_saved(VMRegImpl::stack2reg(xmm15_off + additional_frame_slots), xmm15->as_VMReg());
 200 
 201   // %%% These should all be a waste but we'll keep things as they were for now
 202   if (true) {
 203     map->set_callee_saved(VMRegImpl::stack2reg( raxH_off  + additional_frame_slots), 
 204                           rax->as_VMReg()->next());
 205     map->set_callee_saved(VMRegImpl::stack2reg( rcxH_off  + additional_frame_slots),
 206                           rcx->as_VMReg()->next());
 207     map->set_callee_saved(VMRegImpl::stack2reg( rdxH_off  + additional_frame_slots),
 208                           rdx->as_VMReg()->next());
 209     map->set_callee_saved(VMRegImpl::stack2reg( rbxH_off  + additional_frame_slots),
 210                           rbx->as_VMReg()->next());
 211     // rbp location is known implicitly by the frame sender code, needs no oopmap
 212     map->set_callee_saved(VMRegImpl::stack2reg( rsiH_off  + additional_frame_slots),
 213                           rsi->as_VMReg()->next());
 214     map->set_callee_saved(VMRegImpl::stack2reg( rdiH_off  + additional_frame_slots),
 215                           rdi->as_VMReg()->next());
 216     map->set_callee_saved(VMRegImpl::stack2reg( r8H_off   + additional_frame_slots),
 217                           r8->as_VMReg()->next());
 218     map->set_callee_saved(VMRegImpl::stack2reg( r9H_off   + additional_frame_slots),
 219                           r9->as_VMReg()->next());
 220     map->set_callee_saved(VMRegImpl::stack2reg( r10H_off  + additional_frame_slots),
 221                           r10->as_VMReg()->next());
 222     map->set_callee_saved(VMRegImpl::stack2reg( r11H_off  + additional_frame_slots),
 223                           r11->as_VMReg()->next());
 224     map->set_callee_saved(VMRegImpl::stack2reg( r12H_off  + additional_frame_slots),
 225                           r12->as_VMReg()->next());
 226     map->set_callee_saved(VMRegImpl::stack2reg( r13H_off  + additional_frame_slots),
 227                           r13->as_VMReg()->next());
 228     map->set_callee_saved(VMRegImpl::stack2reg( r14H_off  + additional_frame_slots),
 229                           r14->as_VMReg()->next());
 230     map->set_callee_saved(VMRegImpl::stack2reg( r15H_off  + additional_frame_slots),
 231                           r15->as_VMReg()->next());
 232     map->set_callee_saved(VMRegImpl::stack2reg(xmm0H_off  + additional_frame_slots),
 233                           xmm0->as_VMReg()->next());
 234     map->set_callee_saved(VMRegImpl::stack2reg(xmm1H_off  + additional_frame_slots),
 235                           xmm1->as_VMReg()->next());
 236     map->set_callee_saved(VMRegImpl::stack2reg(xmm2H_off  + additional_frame_slots),
 237                           xmm2->as_VMReg()->next());
 238     map->set_callee_saved(VMRegImpl::stack2reg(xmm3H_off  + additional_frame_slots),
 239                           xmm3->as_VMReg()->next());
 240     map->set_callee_saved(VMRegImpl::stack2reg(xmm4H_off  + additional_frame_slots),
 241                           xmm4->as_VMReg()->next());
 242     map->set_callee_saved(VMRegImpl::stack2reg(xmm5H_off  + additional_frame_slots),
 243                           xmm5->as_VMReg()->next());
 244     map->set_callee_saved(VMRegImpl::stack2reg(xmm6H_off  + additional_frame_slots),
 245                           xmm6->as_VMReg()->next());
 246     map->set_callee_saved(VMRegImpl::stack2reg(xmm7H_off  + additional_frame_slots),
 247                           xmm7->as_VMReg()->next());
 248     map->set_callee_saved(VMRegImpl::stack2reg(xmm8H_off  + additional_frame_slots),
 249                           xmm8->as_VMReg()->next());
 250     map->set_callee_saved(VMRegImpl::stack2reg(xmm9H_off  + additional_frame_slots),
 251                           xmm9->as_VMReg()->next());
 252     map->set_callee_saved(VMRegImpl::stack2reg(xmm10H_off + additional_frame_slots),
 253                           xmm10->as_VMReg()->next());
 254     map->set_callee_saved(VMRegImpl::stack2reg(xmm11H_off + additional_frame_slots),
 255                           xmm11->as_VMReg()->next());
 256     map->set_callee_saved(VMRegImpl::stack2reg(xmm12H_off + additional_frame_slots),
 257                           xmm12->as_VMReg()->next());
 258     map->set_callee_saved(VMRegImpl::stack2reg(xmm13H_off + additional_frame_slots),
 259                           xmm13->as_VMReg()->next());
 260     map->set_callee_saved(VMRegImpl::stack2reg(xmm14H_off + additional_frame_slots),
 261                           xmm14->as_VMReg()->next());
 262     map->set_callee_saved(VMRegImpl::stack2reg(xmm15H_off + additional_frame_slots),
 263                           xmm15->as_VMReg()->next());
 264   }
 265 
 266   return map;
 267 }
 268 
 269 void RegisterSaver::restore_live_registers(MacroAssembler* masm) {
 270   if (frame::arg_reg_save_area_bytes != 0) {
 271     // Pop arg register save area
 272     __ addq(rsp, frame::arg_reg_save_area_bytes);
 273   }
 274   // Recover CPU state
 275   __ pop_CPU_state();
 276   // Get the rbp described implicitly by the calling convention (no oopMap)
 277   __ popq(rbp);
 278 }
 279 
 280 void RegisterSaver::restore_result_registers(MacroAssembler* masm) {
 281 
 282   // Just restore result register. Only used by deoptimization. By
 283   // now any callee save register that needs to be restored to a c2
 284   // caller of the deoptee has been extracted into the vframeArray
 285   // and will be stuffed into the c2i adapter we create for later
 286   // restoration so only result registers need to be restored here.
 287 
 288   // Restore fp result register
 289   __ movdbl(xmm0, Address(rsp, xmm0_offset_in_bytes()));
 290   // Restore integer result register
 291   __ movq(rax, Address(rsp, rax_offset_in_bytes()));
 292   // Pop all of the register save are off the stack except the return address
 293   __ addq(rsp, return_offset_in_bytes());
 294 }
 295 
 296 // The java_calling_convention describes stack locations as ideal slots on
 297 // a frame with no abi restrictions. Since we must observe abi restrictions
 298 // (like the placement of the register window) the slots must be biased by
 299 // the following value.
 300 static int reg2offset_in(VMReg r) { 
 301   // Account for saved rbp and return address
 302   // This should really be in_preserve_stack_slots
 303   return (r->reg2stack() + 4) * VMRegImpl::stack_slot_size;
 304 }
 305 
 306 static int reg2offset_out(VMReg r) { 
 307   return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
 308 }
 309 
 310 // ---------------------------------------------------------------------------
 311 // Read the array of BasicTypes from a signature, and compute where the
 312 // arguments should go.  Values in the VMRegPair regs array refer to 4-byte
 313 // quantities.  Values less than VMRegImpl::stack0 are registers, those above
 314 // refer to 4-byte stack slots.  All stack slots are based off of the stack pointer
 315 // as framesizes are fixed.
 316 // VMRegImpl::stack0 refers to the first slot 0(sp).
 317 // and VMRegImpl::stack0+1 refers to the memory word 4-byes higher.  Register
 318 // up to RegisterImpl::number_of_registers) are the 64-bit
 319 // integer registers.  
 320 
 321 // Note: the INPUTS in sig_bt are in units of Java argument words, which are
 322 // either 32-bit or 64-bit depending on the build.  The OUTPUTS are in 32-bit
 323 // units regardless of build. Of course for i486 there is no 64 bit build
 324 
 325 // The Java calling convention is a "shifted" version of the C ABI.
 326 // By skipping the first C ABI register we can call non-static jni methods
 327 // with small numbers of arguments without having to shuffle the arguments
 328 // at all. Since we control the java ABI we ought to at least get some
 329 // advantage out of it.
 330 
 331 int SharedRuntime::java_calling_convention(const BasicType *sig_bt,
 332                                            VMRegPair *regs,
 333                                            int total_args_passed,
 334                                            int is_outgoing) {
 335 
 336   // Create the mapping between argument positions and
 337   // registers. 
 338   static const Register INT_ArgReg[Argument::n_int_register_parameters_j] = {
 339     j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5
 340   };
 341   static const XMMRegister FP_ArgReg[Argument::n_float_register_parameters_j] = {
 342     j_farg0, j_farg1, j_farg2, j_farg3,
 343     j_farg4, j_farg5, j_farg6, j_farg7
 344   };
 345 
 346 
 347   uint int_args = 0;
 348   uint fp_args = 0;
 349   uint stk_args = 0; // inc by 2 each time
 350 
 351   for (int i = 0; i < total_args_passed; i++) {
 352     switch (sig_bt[i]) {
 353     case T_BOOLEAN:
 354     case T_CHAR:
 355     case T_BYTE:
 356     case T_SHORT:
 357     case T_INT:
 358       if (int_args < Argument::n_int_register_parameters_j) {
 359         regs[i].set1(INT_ArgReg[int_args++]->as_VMReg());
 360       } else {
 361         regs[i].set1(VMRegImpl::stack2reg(stk_args));
 362         stk_args += 2;
 363       }
 364       break;
 365     case T_VOID:
 366       // halves of T_LONG or T_DOUBLE
 367       assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
 368       regs[i].set_bad();
 369       break;
 370     case T_LONG:
 371       assert(sig_bt[i + 1] == T_VOID, "expecting half");
 372       // fall through
 373     case T_OBJECT:
 374     case T_ARRAY:
 375     case T_ADDRESS:
 376       if (int_args < Argument::n_int_register_parameters_j) {
 377         regs[i].set2(INT_ArgReg[int_args++]->as_VMReg());
 378       } else {
 379         regs[i].set2(VMRegImpl::stack2reg(stk_args));
 380         stk_args += 2;
 381       }
 382       break;
 383     case T_FLOAT:
 384       if (fp_args < Argument::n_float_register_parameters_j) {
 385         regs[i].set1(FP_ArgReg[fp_args++]->as_VMReg());
 386       } else {
 387         regs[i].set1(VMRegImpl::stack2reg(stk_args));
 388         stk_args += 2;
 389       }
 390       break;
 391     case T_DOUBLE:
 392       assert(sig_bt[i + 1] == T_VOID, "expecting half");
 393       if (fp_args < Argument::n_float_register_parameters_j) {
 394         regs[i].set2(FP_ArgReg[fp_args++]->as_VMReg());
 395       } else {
 396         regs[i].set2(VMRegImpl::stack2reg(stk_args));
 397         stk_args += 2;
 398       }
 399       break;
 400     default:
 401       ShouldNotReachHere();
 402       break;
 403     }
 404   }
 405 
 406   return round_to(stk_args, 2);
 407 }
 408 
 409 // Patch the callers callsite with entry to compiled code if it exists.
 410 static void patch_callers_callsite(MacroAssembler *masm) {
 411   Label L;
 412   __ verify_oop(rbx);
 413   __ cmpq(Address(rbx, in_bytes(methodOopDesc::code_offset())), (int)NULL_WORD);
 414   __ jcc(Assembler::equal, L);
 415 
 416   // Save the current stack pointer
 417   __ movq(r13, rsp);
 418   // Schedule the branch target address early.
 419   // Call into the VM to patch the caller, then jump to compiled callee
 420   // rax isn't live so capture return address while we easily can
 421   __ movq(rax, Address(rsp, 0));
 422 
 423   // align stack so push_CPU_state doesn't fault
 424   __ andq(rsp, -(StackAlignmentInBytes));
 425   __ push_CPU_state();
 426 
 427 
 428   __ verify_oop(rbx);
 429   // VM needs caller's callsite
 430   // VM needs target method
 431   // This needs to be a long call since we will relocate this adapter to
 432   // the codeBuffer and it may not reach
 433 
 434   // Allocate argument register save area
 435   if (frame::arg_reg_save_area_bytes != 0) {
 436     __ subq(rsp, frame::arg_reg_save_area_bytes);
 437   }
 438   __ movq(c_rarg0, rbx);
 439   __ movq(c_rarg1, rax);
 440   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::fixup_callers_callsite)));
 441 
 442   // De-allocate argument register save area
 443   if (frame::arg_reg_save_area_bytes != 0) {
 444     __ addq(rsp, frame::arg_reg_save_area_bytes);
 445   }
 446 
 447   __ pop_CPU_state();
 448   // restore sp
 449   __ movq(rsp, r13);
 450   __ bind(L);
 451 }
 452 
 453 // Helper function to put tags in interpreter stack.
 454 static void  tag_stack(MacroAssembler *masm, const BasicType sig, int st_off) {
 455   if (TaggedStackInterpreter) {
 456     int tag_offset = st_off + Interpreter::expr_tag_offset_in_bytes(0);
 457     if (sig == T_OBJECT || sig == T_ARRAY) {
 458       __ mov64(Address(rsp, tag_offset), frame::TagReference);
 459     } else if (sig == T_LONG || sig == T_DOUBLE) {
 460       int next_tag_offset = st_off + Interpreter::expr_tag_offset_in_bytes(1);
 461       __ mov64(Address(rsp, next_tag_offset), frame::TagValue);
 462       __ mov64(Address(rsp, tag_offset), frame::TagValue);
 463     } else {
 464       __ mov64(Address(rsp, tag_offset), frame::TagValue);
 465     }
 466   }
 467 }
 468 
 469 
 470 static void gen_c2i_adapter(MacroAssembler *masm,
 471                             int total_args_passed,
 472                             int comp_args_on_stack,
 473                             const BasicType *sig_bt,
 474                             const VMRegPair *regs,
 475                             Label& skip_fixup) {
 476   // Before we get into the guts of the C2I adapter, see if we should be here
 477   // at all.  We've come from compiled code and are attempting to jump to the
 478   // interpreter, which means the caller made a static call to get here
 479   // (vcalls always get a compiled target if there is one).  Check for a
 480   // compiled target.  If there is one, we need to patch the caller's call.
 481   patch_callers_callsite(masm);
 482 
 483   __ bind(skip_fixup);
 484 
 485   // Since all args are passed on the stack, total_args_passed * 
 486   // Interpreter::stackElementSize is the space we need. Plus 1 because 
 487   // we also account for the return address location since
 488   // we store it first rather than hold it in rax across all the shuffling
 489 
 490   int extraspace = (total_args_passed * Interpreter::stackElementSize()) + wordSize;
 491 
 492   // stack is aligned, keep it that way
 493   extraspace = round_to(extraspace, 2*wordSize);
 494 
 495   // Get return address
 496   __ popq(rax);
 497 
 498   // set senderSP value
 499   __ movq(r13, rsp);
 500 
 501   __ subq(rsp, extraspace);
 502 
 503   // Store the return address in the expected location
 504   __ movq(Address(rsp, 0), rax);
 505 
 506   // Now write the args into the outgoing interpreter space
 507   for (int i = 0; i < total_args_passed; i++) {
 508     if (sig_bt[i] == T_VOID) {
 509       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
 510       continue;
 511     }
 512 
 513     // offset to start parameters
 514     int st_off   = (total_args_passed - i) * Interpreter::stackElementSize() + 
 515                    Interpreter::value_offset_in_bytes();
 516     int next_off = st_off - Interpreter::stackElementSize();
 517 
 518     // Say 4 args:
 519     // i   st_off
 520     // 0   32 T_LONG
 521     // 1   24 T_VOID
 522     // 2   16 T_OBJECT
 523     // 3    8 T_BOOL
 524     // -    0 return address
 525     //
 526     // However to make thing extra confusing. Because we can fit a long/double in
 527     // a single slot on a 64 bt vm and it would be silly to break them up, the interpreter
 528     // leaves one slot empty and only stores to a single slot. In this case the
 529     // slot that is occupied is the T_VOID slot. See I said it was confusing.
 530 
 531     VMReg r_1 = regs[i].first();
 532     VMReg r_2 = regs[i].second();
 533     if (!r_1->is_valid()) {
 534       assert(!r_2->is_valid(), "");
 535       continue;
 536     }
 537     if (r_1->is_stack()) { 
 538       // memory to memory use rax
 539       int ld_off = r_1->reg2stack() * VMRegImpl::stack_slot_size + extraspace;
 540       if (!r_2->is_valid()) {
 541         // sign extend??
 542         __ movl(rax, Address(rsp, ld_off));
 543         __ movq(Address(rsp, st_off), rax);
 544         tag_stack(masm, sig_bt[i], st_off);
 545 
 546       } else {
 547 
 548         __ movq(rax, Address(rsp, ld_off));
 549 
 550         // Two VMREgs|OptoRegs can be T_OBJECT, T_ADDRESS, T_DOUBLE, T_LONG
 551         // T_DOUBLE and T_LONG use two slots in the interpreter
 552         if ( sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
 553           // ld_off == LSW, ld_off+wordSize == MSW
 554           // st_off == MSW, next_off == LSW
 555           __ movq(Address(rsp, next_off), rax);
 556 #ifdef ASSERT
 557           // Overwrite the unused slot with known junk
 558           __ mov64(rax, CONST64(0xdeadffffdeadaaaa));
 559           __ movq(Address(rsp, st_off), rax);
 560 #endif /* ASSERT */
 561           tag_stack(masm, sig_bt[i], next_off);
 562         } else {
 563           __ movq(Address(rsp, st_off), rax);
 564           tag_stack(masm, sig_bt[i], st_off);
 565         }
 566       }
 567     } else if (r_1->is_Register()) {
 568       Register r = r_1->as_Register();
 569       if (!r_2->is_valid()) {
 570         // must be only an int (or less ) so move only 32bits to slot
 571         // why not sign extend??
 572         __ movl(Address(rsp, st_off), r);
 573         tag_stack(masm, sig_bt[i], st_off);
 574       } else {
 575         // Two VMREgs|OptoRegs can be T_OBJECT, T_ADDRESS, T_DOUBLE, T_LONG
 576         // T_DOUBLE and T_LONG use two slots in the interpreter
 577         if ( sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
 578           // long/double in gpr
 579 #ifdef ASSERT
 580           // Overwrite the unused slot with known junk
 581           __ mov64(rax, CONST64(0xdeadffffdeadaaab));
 582           __ movq(Address(rsp, st_off), rax);
 583 #endif /* ASSERT */
 584           __ movq(Address(rsp, next_off), r);
 585           tag_stack(masm, sig_bt[i], next_off);
 586         } else {
 587           __ movq(Address(rsp, st_off), r);
 588           tag_stack(masm, sig_bt[i], st_off);
 589         }
 590       }
 591     } else {
 592       assert(r_1->is_XMMRegister(), "");
 593       if (!r_2->is_valid()) {
 594         // only a float use just part of the slot
 595         __ movflt(Address(rsp, st_off), r_1->as_XMMRegister());
 596         tag_stack(masm, sig_bt[i], st_off);
 597       } else {
 598 #ifdef ASSERT
 599         // Overwrite the unused slot with known junk
 600         __ mov64(rax, CONST64(0xdeadffffdeadaaac));
 601         __ movq(Address(rsp, st_off), rax);
 602 #endif /* ASSERT */
 603         __ movdbl(Address(rsp, next_off), r_1->as_XMMRegister());
 604         tag_stack(masm, sig_bt[i], next_off);
 605       }
 606     }
 607   }
 608 
 609   // Schedule the branch target address early.
 610   __ movq(rcx, Address(rbx, in_bytes(methodOopDesc::interpreter_entry_offset())));
 611   __ jmp(rcx);
 612 }
 613 
 614 static void gen_i2c_adapter(MacroAssembler *masm,
 615                             int total_args_passed,
 616                             int comp_args_on_stack,
 617                             const BasicType *sig_bt,
 618                             const VMRegPair *regs) {
 619 
 620   //
 621   // We will only enter here from an interpreted frame and never from after
 622   // passing thru a c2i. Azul allowed this but we do not. If we lose the
 623   // race and use a c2i we will remain interpreted for the race loser(s).
 624   // This removes all sorts of headaches on the x86 side and also eliminates
 625   // the possibility of having c2i -> i2c -> c2i -> ... endless transitions.
 626 
 627 
 628   // Note: r13 contains the senderSP on entry. We must preserve it since
 629   // we may do a i2c -> c2i transition if we lose a race where compiled
 630   // code goes non-entrant while we get args ready.
 631   // In addition we use r13 to locate all the interpreter args as
 632   // we must align the stack to 16 bytes on an i2c entry else we
 633   // lose alignment we expect in all compiled code and register
 634   // save code can segv when fxsave instructions find improperly
 635   // aligned stack pointer.
 636 
 637   __ movq(rax, Address(rsp, 0));
 638 
 639   // Cut-out for having no stack args.  Since up to 2 int/oop args are passed
 640   // in registers, we will occasionally have no stack args.
 641   int comp_words_on_stack = 0;
 642   if (comp_args_on_stack) {
 643     // Sig words on the stack are greater-than VMRegImpl::stack0.  Those in
 644     // registers are below.  By subtracting stack0, we either get a negative
 645     // number (all values in registers) or the maximum stack slot accessed.
 646     
 647     // Convert 4-byte c2 stack slots to words.
 648     comp_words_on_stack = round_to(comp_args_on_stack*VMRegImpl::stack_slot_size, wordSize)>>LogBytesPerWord;
 649     // Round up to miminum stack alignment, in wordSize
 650     comp_words_on_stack = round_to(comp_words_on_stack, 2);
 651     __ subq(rsp, comp_words_on_stack * wordSize);
 652   }
 653 
 654 
 655   // Ensure compiled code always sees stack at proper alignment
 656   __ andq(rsp, -16);
 657 
 658   // push the return address and misalign the stack that youngest frame always sees
 659   // as far as the placement of the call instruction
 660   __ pushq(rax);
 661  
 662   // Will jump to the compiled code just as if compiled code was doing it.
 663   // Pre-load the register-jump target early, to schedule it better.
 664   __ movq(r11, Address(rbx, in_bytes(methodOopDesc::from_compiled_offset())));
 665 
 666   // Now generate the shuffle code.  Pick up all register args and move the
 667   // rest through the floating point stack top.
 668   for (int i = 0; i < total_args_passed; i++) {
 669     if (sig_bt[i] == T_VOID) {
 670       // Longs and doubles are passed in native word order, but misaligned
 671       // in the 32-bit build.
 672       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
 673       continue;
 674     }
 675 
 676     // Pick up 0, 1 or 2 words from SP+offset.  
 677     
 678     assert(!regs[i].second()->is_valid() || regs[i].first()->next() == regs[i].second(),
 679             "scrambled load targets?");
 680     // Load in argument order going down.
 681     // int ld_off = (total_args_passed + comp_words_on_stack -i)*wordSize;
 682     // base ld_off on r13 (sender_sp) as the stack alignment makes offsets from rsp
 683     // unpredictable
 684     int ld_off = ((total_args_passed - 1) - i)*Interpreter::stackElementSize();
 685 
 686     // Point to interpreter value (vs. tag)
 687     int next_off = ld_off - Interpreter::stackElementSize();
 688     //
 689     //  
 690     //
 691     VMReg r_1 = regs[i].first();
 692     VMReg r_2 = regs[i].second();
 693     if (!r_1->is_valid()) {
 694       assert(!r_2->is_valid(), "");
 695       continue;
 696     }
 697     if (r_1->is_stack()) { 
 698       // Convert stack slot to an SP offset (+ wordSize to account for return address )
 699       int st_off = regs[i].first()->reg2stack()*VMRegImpl::stack_slot_size + wordSize;
 700       if (!r_2->is_valid()) {
 701         // sign extend???
 702         __ movl(rax, Address(r13, ld_off));
 703         __ movq(Address(rsp, st_off), rax);
 704       } else {
 705         //
 706         // We are using two optoregs. This can be either T_OBJECT, T_ADDRESS, T_LONG, or T_DOUBLE
 707         // the interpreter allocates two slots but only uses one for thr T_LONG or T_DOUBLE case
 708         // So we must adjust where to pick up the data to match the interpreter.
 709         //
 710         // Interpreter local[n] == MSW, local[n+1] == LSW however locals
 711         // are accessed as negative so LSW is at LOW address
 712 
 713         // ld_off is MSW so get LSW
 714         const int offset = (sig_bt[i]==T_LONG||sig_bt[i]==T_DOUBLE)? 
 715                            next_off : ld_off;
 716         __ movq(rax, Address(r13, offset));
 717         // st_off is LSW (i.e. reg.first())
 718         __ movq(Address(rsp, st_off), rax);
 719       }
 720     } else if (r_1->is_Register()) {  // Register argument
 721       Register r = r_1->as_Register();
 722       assert(r != rax, "must be different");
 723       if (r_2->is_valid()) {
 724         //
 725         // We are using two VMRegs. This can be either T_OBJECT, T_ADDRESS, T_LONG, or T_DOUBLE
 726         // the interpreter allocates two slots but only uses one for thr T_LONG or T_DOUBLE case
 727         // So we must adjust where to pick up the data to match the interpreter.
 728 
 729         const int offset = (sig_bt[i]==T_LONG||sig_bt[i]==T_DOUBLE)? 
 730                            next_off : ld_off;
 731 
 732         // this can be a misaligned move
 733         __ movq(r, Address(r13, offset));
 734       } else {
 735         // sign extend and use a full word?
 736         __ movl(r, Address(r13, ld_off));
 737       }
 738     } else {
 739       if (!r_2->is_valid()) {
 740         __ movflt(r_1->as_XMMRegister(), Address(r13, ld_off));
 741       } else {
 742         __ movdbl(r_1->as_XMMRegister(), Address(r13, next_off));
 743       }
 744     }
 745   }
 746 
 747   // 6243940 We might end up in handle_wrong_method if
 748   // the callee is deoptimized as we race thru here. If that
 749   // happens we don't want to take a safepoint because the
 750   // caller frame will look interpreted and arguments are now
 751   // "compiled" so it is much better to make this transition
 752   // invisible to the stack walking code. Unfortunately if
 753   // we try and find the callee by normal means a safepoint
 754   // is possible. So we stash the desired callee in the thread
 755   // and the vm will find there should this case occur.
 756 
 757   __ movq(Address(r15_thread, JavaThread::callee_target_offset()), rbx);
 758 
 759   // put methodOop where a c2i would expect should we end up there
 760   // only needed becaus eof c2 resolve stubs return methodOop as a result in
 761   // rax 
 762   __ movq(rax, rbx);
 763   __ jmp(r11);
 764 }
 765 
 766 // ---------------------------------------------------------------
 767 AdapterHandlerEntry* SharedRuntime::generate_i2c2i_adapters(MacroAssembler *masm,
 768                                                             int total_args_passed,
 769                                                             int comp_args_on_stack,
 770                                                             const BasicType *sig_bt,
 771                                                             const VMRegPair *regs) {
 772   address i2c_entry = __ pc();
 773 
 774   gen_i2c_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs);
 775 
 776   // -------------------------------------------------------------------------
 777   // Generate a C2I adapter.  On entry we know rbx holds the methodOop during calls
 778   // to the interpreter.  The args start out packed in the compiled layout.  They
 779   // need to be unpacked into the interpreter layout.  This will almost always
 780   // require some stack space.  We grow the current (compiled) stack, then repack
 781   // the args.  We  finally end in a jump to the generic interpreter entry point.
 782   // On exit from the interpreter, the interpreter will restore our SP (lest the
 783   // compiled code, which relys solely on SP and not RBP, get sick).
 784 
 785   address c2i_unverified_entry = __ pc();
 786   Label skip_fixup;
 787   Label ok;
 788 
 789   Register holder = rax;
 790   Register receiver = j_rarg0;
 791   Register temp = rbx;
 792 
 793   {
 794     __ verify_oop(holder);
 795     __ movq(temp, Address(receiver, oopDesc::klass_offset_in_bytes()));
 796     __ verify_oop(temp);
 797     
 798     __ cmpq(temp, Address(holder, compiledICHolderOopDesc::holder_klass_offset()));
 799     __ movq(rbx, Address(holder, compiledICHolderOopDesc::holder_method_offset()));
 800     __ jcc(Assembler::equal, ok);
 801     __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 802 
 803     __ bind(ok);
 804     // Method might have been compiled since the call site was patched to
 805     // interpreted if that is the case treat it as a miss so we can get
 806     // the call site corrected.
 807     __ cmpq(Address(rbx, in_bytes(methodOopDesc::code_offset())), (int)NULL_WORD);
 808     __ jcc(Assembler::equal, skip_fixup);
 809     __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 810   }
 811 
 812   address c2i_entry = __ pc();
 813 
 814   gen_c2i_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs, skip_fixup);
 815 
 816   __ flush();
 817   return new AdapterHandlerEntry(i2c_entry, c2i_entry, c2i_unverified_entry);
 818 }
 819 
 820 int SharedRuntime::c_calling_convention(const BasicType *sig_bt, 
 821                                          VMRegPair *regs,
 822                                          int total_args_passed) {
 823 // We return the amount of VMRegImpl stack slots we need to reserve for all
 824 // the arguments NOT counting out_preserve_stack_slots. 
 825 
 826 // NOTE: These arrays will have to change when c1 is ported
 827 #ifdef _WIN64
 828     static const Register INT_ArgReg[Argument::n_int_register_parameters_c] = {
 829       c_rarg0, c_rarg1, c_rarg2, c_rarg3
 830     };
 831     static const XMMRegister FP_ArgReg[Argument::n_float_register_parameters_c] = {
 832       c_farg0, c_farg1, c_farg2, c_farg3
 833     };
 834 #else
 835     static const Register INT_ArgReg[Argument::n_int_register_parameters_c] = {
 836       c_rarg0, c_rarg1, c_rarg2, c_rarg3, c_rarg4, c_rarg5
 837     };
 838     static const XMMRegister FP_ArgReg[Argument::n_float_register_parameters_c] = {
 839       c_farg0, c_farg1, c_farg2, c_farg3,
 840       c_farg4, c_farg5, c_farg6, c_farg7
 841     };
 842 #endif // _WIN64
 843 
 844 
 845     uint int_args = 0;
 846     uint fp_args = 0;
 847     uint stk_args = 0; // inc by 2 each time
 848 
 849     for (int i = 0; i < total_args_passed; i++) {
 850       switch (sig_bt[i]) {
 851       case T_BOOLEAN:
 852       case T_CHAR:
 853       case T_BYTE:
 854       case T_SHORT:
 855       case T_INT:
 856         if (int_args < Argument::n_int_register_parameters_c) {
 857           regs[i].set1(INT_ArgReg[int_args++]->as_VMReg());
 858 #ifdef _WIN64
 859           fp_args++;
 860           // Allocate slots for callee to stuff register args the stack.
 861           stk_args += 2;
 862 #endif
 863         } else {
 864           regs[i].set1(VMRegImpl::stack2reg(stk_args));
 865           stk_args += 2;
 866         }
 867         break;
 868       case T_LONG:
 869         assert(sig_bt[i + 1] == T_VOID, "expecting half");
 870         // fall through
 871       case T_OBJECT:
 872       case T_ARRAY:
 873       case T_ADDRESS:
 874         if (int_args < Argument::n_int_register_parameters_c) {
 875           regs[i].set2(INT_ArgReg[int_args++]->as_VMReg());
 876 #ifdef _WIN64
 877           fp_args++;
 878           stk_args += 2;
 879 #endif
 880         } else {
 881           regs[i].set2(VMRegImpl::stack2reg(stk_args));
 882           stk_args += 2;
 883         }
 884         break;
 885       case T_FLOAT:
 886         if (fp_args < Argument::n_float_register_parameters_c) {
 887           regs[i].set1(FP_ArgReg[fp_args++]->as_VMReg());
 888 #ifdef _WIN64
 889           int_args++;
 890           // Allocate slots for callee to stuff register args the stack.
 891           stk_args += 2;
 892 #endif
 893         } else {
 894           regs[i].set1(VMRegImpl::stack2reg(stk_args));
 895           stk_args += 2;
 896         }
 897         break;
 898       case T_DOUBLE:
 899         assert(sig_bt[i + 1] == T_VOID, "expecting half");
 900         if (fp_args < Argument::n_float_register_parameters_c) {
 901           regs[i].set2(FP_ArgReg[fp_args++]->as_VMReg());
 902 #ifdef _WIN64
 903           int_args++;
 904           // Allocate slots for callee to stuff register args the stack.
 905           stk_args += 2;
 906 #endif
 907         } else {
 908           regs[i].set2(VMRegImpl::stack2reg(stk_args));
 909           stk_args += 2;
 910         }
 911         break;
 912       case T_VOID: // Halves of longs and doubles
 913         assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
 914         regs[i].set_bad();
 915         break;
 916       default:
 917         ShouldNotReachHere();
 918         break;
 919       }
 920     }
 921 #ifdef _WIN64
 922   // windows abi requires that we always allocate enough stack space 
 923   // for 4 64bit registers to be stored down.
 924   if (stk_args < 8) {
 925     stk_args = 8;
 926   }
 927 #endif // _WIN64
 928   
 929   return stk_args;
 930 }
 931 
 932 // On 64 bit we will store integer like items to the stack as
 933 // 64 bits items (sparc abi) even though java would only store
 934 // 32bits for a parameter. On 32bit it will simply be 32 bits
 935 // So this routine will do 32->32 on 32bit and 32->64 on 64bit
 936 static void move32_64(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
 937   if (src.first()->is_stack()) {
 938     if (dst.first()->is_stack()) {
 939       // stack to stack
 940       __ movslq(rax, Address(rbp, reg2offset_in(src.first())));
 941       __ movq(Address(rsp, reg2offset_out(dst.first())), rax);
 942     } else {
 943       // stack to reg
 944       __ movslq(dst.first()->as_Register(), Address(rbp, reg2offset_in(src.first())));
 945     }
 946   } else if (dst.first()->is_stack()) {
 947     // reg to stack
 948     // Do we really have to sign extend???
 949     // __ movslq(src.first()->as_Register(), src.first()->as_Register());
 950     __ movq(Address(rsp, reg2offset_out(dst.first())), src.first()->as_Register());
 951   } else {
 952     // Do we really have to sign extend???
 953     // __ movslq(dst.first()->as_Register(), src.first()->as_Register());
 954     if (dst.first() != src.first()) {
 955       __ movq(dst.first()->as_Register(), src.first()->as_Register());
 956     }
 957   }
 958 }
 959 
 960 
 961 // An oop arg. Must pass a handle not the oop itself
 962 static void object_move(MacroAssembler* masm, 
 963                         OopMap* map,
 964                         int oop_handle_offset,
 965                         int framesize_in_slots,
 966                         VMRegPair src,
 967                         VMRegPair dst,
 968                         bool is_receiver,
 969                         int* receiver_offset) {
 970 
 971   // must pass a handle. First figure out the location we use as a handle
 972 
 973   Register rHandle = dst.first()->is_stack() ? rax : dst.first()->as_Register();
 974 
 975   // See if oop is NULL if it is we need no handle
 976 
 977   if (src.first()->is_stack()) {
 978 
 979     // Oop is already on the stack as an argument
 980     int offset_in_older_frame = src.first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
 981     map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + framesize_in_slots));
 982     if (is_receiver) {
 983       *receiver_offset = (offset_in_older_frame + framesize_in_slots) * VMRegImpl::stack_slot_size;
 984     }
 985 
 986     __ cmpq(Address(rbp, reg2offset_in(src.first())), (int)NULL_WORD);
 987     __ leaq(rHandle, Address(rbp, reg2offset_in(src.first())));
 988     // conditionally move a NULL
 989     __ cmovq(Assembler::equal, rHandle, Address(rbp, reg2offset_in(src.first())));
 990   } else {
 991 
 992     // Oop is in an a register we must store it to the space we reserve
 993     // on the stack for oop_handles and pass a handle if oop is non-NULL
 994 
 995     const Register rOop = src.first()->as_Register();
 996     int oop_slot;
 997     if (rOop == j_rarg0)
 998       oop_slot = 0;
 999     else if (rOop == j_rarg1)
1000       oop_slot = 1;
1001     else if (rOop == j_rarg2)
1002       oop_slot = 2;
1003     else if (rOop == j_rarg3)
1004       oop_slot = 3;
1005     else if (rOop == j_rarg4)
1006       oop_slot = 4;
1007     else {
1008       assert(rOop == j_rarg5, "wrong register");
1009       oop_slot = 5;
1010     }
1011 
1012     oop_slot = oop_slot * VMRegImpl::slots_per_word + oop_handle_offset;
1013     int offset = oop_slot*VMRegImpl::stack_slot_size;
1014 
1015     map->set_oop(VMRegImpl::stack2reg(oop_slot));
1016     // Store oop in handle area, may be NULL
1017     __ movq(Address(rsp, offset), rOop);
1018     if (is_receiver) {
1019       *receiver_offset = offset;
1020     }
1021 
1022     __ cmpq(rOop, (int)NULL);
1023     __ leaq(rHandle, Address(rsp, offset));
1024     // conditionally move a NULL from the handle area where it was just stored
1025     __ cmovq(Assembler::equal, rHandle, Address(rsp, offset));
1026   }
1027 
1028   // If arg is on the stack then place it otherwise it is already in correct reg.
1029   if (dst.first()->is_stack()) {
1030     __ movq(Address(rsp, reg2offset_out(dst.first())), rHandle);
1031   }
1032 }
1033 
1034 // A float arg may have to do float reg int reg conversion
1035 static void float_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1036   assert(!src.second()->is_valid() && !dst.second()->is_valid(), "bad float_move");
1037 
1038   // The calling conventions assures us that each VMregpair is either
1039   // all really one physical register or adjacent stack slots.
1040   // This greatly simplifies the cases here compared to sparc.
1041 
1042   if (src.first()->is_stack()) {
1043     if (dst.first()->is_stack()) {
1044       __ movl(rax, Address(rbp, reg2offset_in(src.first())));
1045       __ movq(Address(rsp, reg2offset_out(dst.first())), rax);
1046     } else {
1047       // stack to reg
1048       assert(dst.first()->is_XMMRegister(), "only expect xmm registers as parameters");
1049       __ movflt(dst.first()->as_XMMRegister(), Address(rbp, reg2offset_in(src.first())));
1050     }
1051   } else if (dst.first()->is_stack()) {
1052     // reg to stack
1053     assert(src.first()->is_XMMRegister(), "only expect xmm registers as parameters");
1054     __ movflt(Address(rsp, reg2offset_out(dst.first())), src.first()->as_XMMRegister());
1055   } else {
1056     // reg to reg
1057     // In theory these overlap but the ordering is such that this is likely a nop
1058     if ( src.first() != dst.first()) {
1059       __ movdbl(dst.first()->as_XMMRegister(),  src.first()->as_XMMRegister());
1060     }
1061   }
1062 }
1063 
1064 // A long move
1065 static void long_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1066 
1067   // The calling conventions assures us that each VMregpair is either
1068   // all really one physical register or adjacent stack slots.
1069   // This greatly simplifies the cases here compared to sparc.
1070 
1071   if (src.is_single_phys_reg() ) {
1072     if (dst.is_single_phys_reg()) {
1073       if (dst.first() != src.first()) {
1074         __ movq(dst.first()->as_Register(), src.first()->as_Register());
1075       }
1076     } else {
1077       assert(dst.is_single_reg(), "not a stack pair");
1078       __ movq(Address(rsp, reg2offset_out(dst.first())), src.first()->as_Register());
1079     }
1080   } else if (dst.is_single_phys_reg()) {
1081     assert(src.is_single_reg(),  "not a stack pair");
1082     __ movq(dst.first()->as_Register(), Address(rbp, reg2offset_out(src.first())));
1083   } else {
1084     assert(src.is_single_reg() && dst.is_single_reg(), "not stack pairs");
1085     __ movq(rax, Address(rbp, reg2offset_in(src.first())));
1086     __ movq(Address(rsp, reg2offset_out(dst.first())), rax);
1087   }
1088 }
1089 
1090 // A double move
1091 static void double_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1092 
1093   // The calling conventions assures us that each VMregpair is either
1094   // all really one physical register or adjacent stack slots.
1095   // This greatly simplifies the cases here compared to sparc.
1096 
1097   if (src.is_single_phys_reg() ) {
1098     if (dst.is_single_phys_reg()) {
1099       // In theory these overlap but the ordering is such that this is likely a nop
1100       if ( src.first() != dst.first()) {
1101         __ movdbl(dst.first()->as_XMMRegister(), src.first()->as_XMMRegister());
1102       }
1103     } else {
1104       assert(dst.is_single_reg(), "not a stack pair");
1105       __ movdbl(Address(rsp, reg2offset_out(dst.first())), src.first()->as_XMMRegister());
1106     }
1107   } else if (dst.is_single_phys_reg()) {
1108     assert(src.is_single_reg(),  "not a stack pair");
1109     __ movdbl(dst.first()->as_XMMRegister(), Address(rbp, reg2offset_out(src.first())));
1110   } else {
1111     assert(src.is_single_reg() && dst.is_single_reg(), "not stack pairs");
1112     __ movq(rax, Address(rbp, reg2offset_in(src.first())));
1113     __ movq(Address(rsp, reg2offset_out(dst.first())), rax);
1114   }
1115 }
1116 
1117 
1118 void SharedRuntime::save_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1119   // We always ignore the frame_slots arg and just use the space just below frame pointer
1120   // which by this time is free to use
1121   switch (ret_type) {
1122   case T_FLOAT:
1123     __ movflt(Address(rbp, -wordSize), xmm0);
1124     break;
1125   case T_DOUBLE:
1126     __ movdbl(Address(rbp, -wordSize), xmm0);
1127     break;
1128   case T_VOID:  break;
1129   default: {
1130     __ movq(Address(rbp, -wordSize), rax);
1131     }
1132   }
1133 }
1134 
1135 void SharedRuntime::restore_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1136   // We always ignore the frame_slots arg and just use the space just below frame pointer
1137   // which by this time is free to use
1138   switch (ret_type) {
1139   case T_FLOAT:
1140     __ movflt(xmm0, Address(rbp, -wordSize));
1141     break;
1142   case T_DOUBLE:
1143     __ movdbl(xmm0, Address(rbp, -wordSize));
1144     break;
1145   case T_VOID:  break;
1146   default: {
1147     __ movq(rax, Address(rbp, -wordSize));
1148     }
1149   }
1150 }
1151 
1152 static void save_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
1153     for ( int i = first_arg ; i < arg_count ; i++ ) {
1154       if (args[i].first()->is_Register()) {
1155         __ pushq(args[i].first()->as_Register());
1156       } else if (args[i].first()->is_XMMRegister()) {
1157         __ subq(rsp, 2*wordSize);
1158         __ movdbl(Address(rsp, 0), args[i].first()->as_XMMRegister());
1159       }
1160     }
1161 }
1162 
1163 static void restore_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
1164     for ( int i = arg_count - 1 ; i >= first_arg ; i-- ) {
1165       if (args[i].first()->is_Register()) {
1166         __ popq(args[i].first()->as_Register());
1167       } else if (args[i].first()->is_XMMRegister()) {
1168         __ movdbl(args[i].first()->as_XMMRegister(), Address(rsp, 0));
1169         __ addq(rsp, 2*wordSize);
1170       }
1171     }
1172 }
1173 
1174 // ---------------------------------------------------------------------------
1175 // Generate a native wrapper for a given method.  The method takes arguments
1176 // in the Java compiled code convention, marshals them to the native
1177 // convention (handlizes oops, etc), transitions to native, makes the call,
1178 // returns to java state (possibly blocking), unhandlizes any result and
1179 // returns.
1180 nmethod *SharedRuntime::generate_native_wrapper(MacroAssembler *masm,
1181                                                 methodHandle method,
1182                                                 int total_in_args,
1183                                                 int comp_args_on_stack,
1184                                                 BasicType *in_sig_bt,
1185                                                 VMRegPair *in_regs,
1186                                                 BasicType ret_type) {
1187   // Native nmethod wrappers never take possesion of the oop arguments.
1188   // So the caller will gc the arguments. The only thing we need an
1189   // oopMap for is if the call is static 
1190   //
1191   // An OopMap for lock (and class if static)
1192   OopMapSet *oop_maps = new OopMapSet();
1193   intptr_t start = (intptr_t)__ pc();
1194 
1195   // We have received a description of where all the java arg are located
1196   // on entry to the wrapper. We need to convert these args to where
1197   // the jni function will expect them. To figure out where they go
1198   // we convert the java signature to a C signature by inserting
1199   // the hidden arguments as arg[0] and possibly arg[1] (static method)
1200 
1201   int total_c_args = total_in_args + 1;
1202   if (method->is_static()) {
1203     total_c_args++;
1204   }
1205 
1206   BasicType* out_sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_c_args);
1207   VMRegPair* out_regs   = NEW_RESOURCE_ARRAY(VMRegPair,   total_c_args);
1208 
1209   int argc = 0;
1210   out_sig_bt[argc++] = T_ADDRESS;
1211   if (method->is_static()) {
1212     out_sig_bt[argc++] = T_OBJECT;
1213   }
1214 
1215   for (int i = 0; i < total_in_args ; i++ ) {
1216     out_sig_bt[argc++] = in_sig_bt[i];
1217   }
1218 
1219   // Now figure out where the args must be stored and how much stack space
1220   // they require.
1221   // 
1222   int out_arg_slots;
1223   out_arg_slots = c_calling_convention(out_sig_bt, out_regs, total_c_args);
1224 
1225   // Compute framesize for the wrapper.  We need to handlize all oops in
1226   // incoming registers 
1227 
1228   // Calculate the total number of stack slots we will need.
1229 
1230   // First count the abi requirement plus all of the outgoing args
1231   int stack_slots = SharedRuntime::out_preserve_stack_slots() + out_arg_slots;
1232 
1233   // Now the space for the inbound oop handle area
1234 
1235   int oop_handle_offset = stack_slots;
1236   stack_slots += 6*VMRegImpl::slots_per_word;
1237 
1238   // Now any space we need for handlizing a klass if static method
1239 
1240   int oop_temp_slot_offset = 0;
1241   int klass_slot_offset = 0;
1242   int klass_offset = -1;
1243   int lock_slot_offset = 0;
1244   bool is_static = false;
1245 
1246   if (method->is_static()) {
1247     klass_slot_offset = stack_slots;
1248     stack_slots += VMRegImpl::slots_per_word;
1249     klass_offset = klass_slot_offset * VMRegImpl::stack_slot_size;
1250     is_static = true;
1251   }
1252 
1253   // Plus a lock if needed
1254 
1255   if (method->is_synchronized()) {
1256     lock_slot_offset = stack_slots;
1257     stack_slots += VMRegImpl::slots_per_word;
1258   }
1259 
1260   // Now a place (+2) to save return values or temp during shuffling
1261   // + 4 for return address (which we own) and saved rbp
1262   stack_slots += 6;
1263 
1264   // Ok The space we have allocated will look like:
1265   //
1266   //
1267   // FP-> |                     |
1268   //      |---------------------|
1269   //      | 2 slots for moves   |
1270   //      |---------------------| 
1271   //      | lock box (if sync)  |
1272   //      |---------------------| <- lock_slot_offset
1273   //      | klass (if static)   |
1274   //      |---------------------| <- klass_slot_offset
1275   //      | oopHandle area      |
1276   //      |---------------------| <- oop_handle_offset (6 java arg registers)
1277   //      | outbound memory     |
1278   //      | based arguments     |
1279   //      |                     |
1280   //      |---------------------| 
1281   //      |                     |
1282   // SP-> | out_preserved_slots |
1283   //
1284   //
1285 
1286 
1287   // Now compute actual number of stack words we need rounding to make 
1288   // stack properly aligned.
1289   stack_slots = round_to(stack_slots, 4 * VMRegImpl::slots_per_word);
1290 
1291   int stack_size = stack_slots * VMRegImpl::stack_slot_size;
1292 
1293 
1294   // First thing make an ic check to see if we should even be here
1295 
1296   // We are free to use all registers as temps without saving them and
1297   // restoring them except rbp. rbp is the only callee save register
1298   // as far as the interpreter and the compiler(s) are concerned.
1299 
1300 
1301   const Register ic_reg = rax;
1302   const Register receiver = j_rarg0;
1303 
1304   Label ok;
1305   Label exception_pending;
1306 
1307   __ verify_oop(receiver);
1308   __ cmpq(ic_reg, Address(receiver, oopDesc::klass_offset_in_bytes()));
1309   __ jcc(Assembler::equal, ok);
1310 
1311   __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
1312 
1313   // Verified entry point must be aligned
1314   __ align(8);
1315 
1316   __ bind(ok);
1317 
1318   int vep_offset = ((intptr_t)__ pc()) - start;
1319 
1320   // The instruction at the verified entry point must be 5 bytes or longer
1321   // because it can be patched on the fly by make_non_entrant. The stack bang
1322   // instruction fits that requirement.
1323 
1324   // Generate stack overflow check
1325   
1326   if (UseStackBanging) {
1327     __ bang_stack_with_offset(StackShadowPages*os::vm_page_size());
1328   } else {
1329     // need a 5 byte instruction to allow MT safe patching to non-entrant
1330     __ fat_nop();
1331   }
1332 
1333   // Generate a new frame for the wrapper.
1334   __ enter();
1335   // -2 because return address is already present and so is saved rbp
1336   __ subq(rsp, stack_size - 2*wordSize);
1337 
1338     // Frame is now completed as far as size and linkage.
1339 
1340     int frame_complete = ((intptr_t)__ pc()) - start;
1341 
1342 #ifdef ASSERT
1343     {
1344       Label L;
1345       __ movq(rax, rsp);
1346       __ andq(rax, -16); // must be 16 byte boundry (see amd64 ABI)
1347       __ cmpq(rax, rsp);
1348       __ jcc(Assembler::equal, L);
1349       __ stop("improperly aligned stack");
1350       __ bind(L);
1351     }
1352 #endif /* ASSERT */
1353 
1354 
1355   // We use r14 as the oop handle for the receiver/klass
1356   // It is callee save so it survives the call to native
1357 
1358   const Register oop_handle_reg = r14;
1359 
1360 
1361 
1362   //
1363   // We immediately shuffle the arguments so that any vm call we have to
1364   // make from here on out (sync slow path, jvmti, etc.) we will have
1365   // captured the oops from our caller and have a valid oopMap for
1366   // them.
1367 
1368   // -----------------
1369   // The Grand Shuffle 
1370 
1371   // The Java calling convention is either equal (linux) or denser (win64) than the 
1372   // c calling convention. However the because of the jni_env argument the c calling
1373   // convention always has at least one more (and two for static) arguments than Java.
1374   // Therefore if we move the args from java -> c backwards then we will never have
1375   // a register->register conflict and we don't have to build a dependency graph
1376   // and figure out how to break any cycles.
1377   //
1378 
1379   // Record esp-based slot for receiver on stack for non-static methods
1380   int receiver_offset = -1;
1381 
1382   // This is a trick. We double the stack slots so we can claim
1383   // the oops in the caller's frame. Since we are sure to have
1384   // more args than the caller doubling is enough to make
1385   // sure we can capture all the incoming oop args from the
1386   // caller. 
1387   //
1388   OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1389 
1390   // Mark location of rbp (someday)
1391   // map->set_callee_saved(VMRegImpl::stack2reg( stack_slots - 2), stack_slots * 2, 0, vmreg(rbp));
1392 
1393   // Use eax, ebx as temporaries during any memory-memory moves we have to do
1394   // All inbound args are referenced based on rbp and all outbound args via rsp.
1395 
1396 
1397 #ifdef ASSERT
1398   bool reg_destroyed[RegisterImpl::number_of_registers];
1399   bool freg_destroyed[XMMRegisterImpl::number_of_registers];
1400   for ( int r = 0 ; r < RegisterImpl::number_of_registers ; r++ ) {
1401     reg_destroyed[r] = false;
1402   }
1403   for ( int f = 0 ; f < XMMRegisterImpl::number_of_registers ; f++ ) {
1404     freg_destroyed[f] = false;
1405   }
1406   
1407 #endif /* ASSERT */
1408 
1409 
1410   int c_arg = total_c_args - 1;
1411   for ( int i = total_in_args - 1; i >= 0 ; i--, c_arg-- ) {
1412 #ifdef ASSERT
1413     if (in_regs[i].first()->is_Register()) {
1414       assert(!reg_destroyed[in_regs[i].first()->as_Register()->encoding()], "destroyed reg!");
1415     } else if (in_regs[i].first()->is_XMMRegister()) {
1416       assert(!freg_destroyed[in_regs[i].first()->as_XMMRegister()->encoding()], "destroyed reg!");
1417     }
1418     if (out_regs[c_arg].first()->is_Register()) {
1419       reg_destroyed[out_regs[c_arg].first()->as_Register()->encoding()] = true;
1420     } else if (out_regs[c_arg].first()->is_XMMRegister()) {
1421       freg_destroyed[out_regs[c_arg].first()->as_XMMRegister()->encoding()] = true;
1422     }
1423 #endif /* ASSERT */
1424     switch (in_sig_bt[i]) {
1425       case T_ARRAY:
1426       case T_OBJECT:
1427         object_move(masm, map, oop_handle_offset, stack_slots, in_regs[i], out_regs[c_arg],
1428                     ((i == 0) && (!is_static)),
1429                     &receiver_offset);
1430         break;
1431       case T_VOID:
1432         break;
1433 
1434       case T_FLOAT:
1435         float_move(masm, in_regs[i], out_regs[c_arg]);
1436           break;
1437 
1438       case T_DOUBLE:
1439         assert( i + 1 < total_in_args && 
1440                 in_sig_bt[i + 1] == T_VOID &&
1441                 out_sig_bt[c_arg+1] == T_VOID, "bad arg list");
1442         double_move(masm, in_regs[i], out_regs[c_arg]);
1443         break;
1444 
1445       case T_LONG :
1446         long_move(masm, in_regs[i], out_regs[c_arg]);
1447         break;
1448 
1449       case T_ADDRESS: assert(false, "found T_ADDRESS in java args");
1450 
1451       default:
1452         move32_64(masm, in_regs[i], out_regs[c_arg]);
1453     }
1454   }
1455 
1456   // point c_arg at the first arg that is already loaded in case we
1457   // need to spill before we call out
1458   c_arg++;
1459 
1460   // Pre-load a static method's oop into r14.  Used both by locking code and
1461   // the normal JNI call code.
1462   if (method->is_static()) {
1463 
1464     //  load oop into a register
1465     __ movoop(oop_handle_reg, JNIHandles::make_local(Klass::cast(method->method_holder())->java_mirror()));
1466 
1467     // Now handlize the static class mirror it's known not-null.
1468     __ movq(Address(rsp, klass_offset), oop_handle_reg);
1469     map->set_oop(VMRegImpl::stack2reg(klass_slot_offset));
1470 
1471     // Now get the handle
1472     __ leaq(oop_handle_reg, Address(rsp, klass_offset));
1473     // store the klass handle as second argument
1474     __ movq(c_rarg1, oop_handle_reg);
1475     // and protect the arg if we must spill
1476     c_arg--;
1477   }
1478 
1479   // Change state to native (we save the return address in the thread, since it might not
1480   // be pushed on the stack when we do a a stack traversal). It is enough that the pc()
1481   // points into the right code segment. It does not have to be the correct return pc.
1482   // We use the same pc/oopMap repeatedly when we call out
1483 
1484   intptr_t the_pc = (intptr_t) __ pc();
1485   oop_maps->add_gc_map(the_pc - start, map);
1486 
1487   __ set_last_Java_frame(rsp, noreg, (address)the_pc);
1488 
1489 
1490   // We have all of the arguments setup at this point. We must not touch any register
1491   // argument registers at this point (what if we save/restore them there are no oop?
1492 
1493   {
1494     SkipIfEqual skip(masm, &DTraceMethodProbes, false);
1495     // protect the args we've loaded
1496     save_args(masm, total_c_args, c_arg, out_regs);
1497     __ movoop(c_rarg1, JNIHandles::make_local(method()));
1498     __ call_VM_leaf(
1499       CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry), 
1500       r15_thread, c_rarg1);
1501     restore_args(masm, total_c_args, c_arg, out_regs);
1502   }
1503 
1504   // Lock a synchronized method
1505 
1506   // Register definitions used by locking and unlocking
1507 
1508   const Register swap_reg = rax;  // Must use rax for cmpxchg instruction
1509   const Register obj_reg  = rbx;  // Will contain the oop
1510   const Register lock_reg = r13;  // Address of compiler lock object (BasicLock)
1511   const Register old_hdr  = r13;  // value of old header at unlock time
1512 
1513   Label slow_path_lock;
1514   Label lock_done;
1515 
1516   if (method->is_synchronized()) {
1517 
1518 
1519     const int mark_word_offset = BasicLock::displaced_header_offset_in_bytes();
1520 
1521     // Get the handle (the 2nd argument)
1522     __ movq(oop_handle_reg, c_rarg1);
1523 
1524     // Get address of the box
1525 
1526     __ leaq(lock_reg, Address(rsp, lock_slot_offset * VMRegImpl::stack_slot_size));
1527 
1528     // Load the oop from the handle 
1529     __ movq(obj_reg, Address(oop_handle_reg, 0));
1530 
1531     if (UseBiasedLocking) {
1532       __ biased_locking_enter(lock_reg, obj_reg, swap_reg, rscratch1, false, lock_done, &slow_path_lock);
1533     }
1534 
1535     // Load immediate 1 into swap_reg %rax
1536     __ movl(swap_reg, 1);
1537 
1538     // Load (object->mark() | 1) into swap_reg %rax
1539     __ orq(swap_reg, Address(obj_reg, 0));
1540 
1541     // Save (object->mark() | 1) into BasicLock's displaced header
1542     __ movq(Address(lock_reg, mark_word_offset), swap_reg);
1543 
1544     if (os::is_MP()) {
1545       __ lock();
1546     }
1547 
1548     // src -> dest iff dest == rax else rax <- dest
1549     __ cmpxchgq(lock_reg, Address(obj_reg, 0));
1550     __ jcc(Assembler::equal, lock_done);
1551 
1552     // Hmm should this move to the slow path code area???
1553 
1554     // Test if the oopMark is an obvious stack pointer, i.e.,
1555     //  1) (mark & 3) == 0, and
1556     //  2) rsp <= mark < mark + os::pagesize()
1557     // These 3 tests can be done by evaluating the following
1558     // expression: ((mark - rsp) & (3 - os::vm_page_size())),
1559     // assuming both stack pointer and pagesize have their
1560     // least significant 2 bits clear.
1561     // NOTE: the oopMark is in swap_reg %rax as the result of cmpxchg
1562 
1563     __ subq(swap_reg, rsp);
1564     __ andq(swap_reg, 3 - os::vm_page_size());
1565 
1566     // Save the test result, for recursive case, the result is zero
1567     __ movq(Address(lock_reg, mark_word_offset), swap_reg);
1568     __ jcc(Assembler::notEqual, slow_path_lock);
1569 
1570     // Slow path will re-enter here
1571 
1572     __ bind(lock_done);
1573   }
1574 
1575 
1576   // Finally just about ready to make the JNI call
1577 
1578 
1579   // get JNIEnv* which is first argument to native
1580 
1581   __ leaq(c_rarg0, Address(r15_thread, in_bytes(JavaThread::jni_environment_offset())));
1582 
1583   // Now set thread in native
1584   __ mov64(Address(r15_thread, JavaThread::thread_state_offset()), _thread_in_native);    
1585 
1586   __ call(RuntimeAddress(method->native_function()));
1587 
1588     // Either restore the MXCSR register after returning from the JNI Call
1589     // or verify that it wasn't changed.
1590     if (RestoreMXCSROnJNICalls) {
1591       __ ldmxcsr(ExternalAddress(StubRoutines::amd64::mxcsr_std()));
1592 
1593     }
1594     else if (CheckJNICalls ) {
1595       __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, StubRoutines::amd64::verify_mxcsr_entry())));
1596     }
1597 
1598 
1599   // Unpack native results.  
1600   switch (ret_type) {
1601   case T_BOOLEAN: __ c2bool(rax);            break;
1602   case T_CHAR   : __ movzwl(rax, rax);      break;
1603   case T_BYTE   : __ sign_extend_byte (rax); break;
1604   case T_SHORT  : __ sign_extend_short(rax); break;
1605   case T_INT    : /* nothing to do */        break;
1606   case T_DOUBLE :
1607   case T_FLOAT  :
1608     // Result is in xmm0 we'll save as needed
1609     break;
1610   case T_ARRAY:                 // Really a handle
1611   case T_OBJECT:                // Really a handle
1612       break; // can't de-handlize until after safepoint check
1613   case T_VOID: break;
1614   case T_LONG: break;
1615   default       : ShouldNotReachHere();
1616   }
1617 
1618   // Switch thread to "native transition" state before reading the synchronization state.
1619   // This additional state is necessary because reading and testing the synchronization
1620   // state is not atomic w.r.t. GC, as this scenario demonstrates:
1621   //     Java thread A, in _thread_in_native state, loads _not_synchronized and is preempted.
1622   //     VM thread changes sync state to synchronizing and suspends threads for GC.
1623   //     Thread A is resumed to finish this native method, but doesn't block here since it
1624   //     didn't see any synchronization is progress, and escapes.
1625   __ mov64(Address(r15_thread, JavaThread::thread_state_offset()), _thread_in_native_trans);    
1626 
1627   if(os::is_MP()) { 
1628     if (UseMembar) {
1629       // Force this write out before the read below
1630       __ membar(Assembler::Membar_mask_bits(
1631            Assembler::LoadLoad | Assembler::LoadStore | 
1632            Assembler::StoreLoad | Assembler::StoreStore));
1633     } else {
1634       // Write serialization page so VM thread can do a pseudo remote membar.
1635       // We use the current thread pointer to calculate a thread specific
1636       // offset to write to within the page. This minimizes bus traffic
1637       // due to cache line collision.
1638       __ serialize_memory(r15_thread, rcx);
1639     }
1640   }
1641 
1642 
1643   // check for safepoint operation in progress and/or pending suspend requests
1644   {
1645     Label Continue;
1646 
1647     __ cmp32(ExternalAddress((address)SafepointSynchronize::address_of_state()),
1648              SafepointSynchronize::_not_synchronized);
1649 
1650     Label L;
1651     __ jcc(Assembler::notEqual, L);
1652     __ cmpl(Address(r15_thread, JavaThread::suspend_flags_offset()), 0);
1653     __ jcc(Assembler::equal, Continue);
1654     __ bind(L);
1655 
1656     // Don't use call_VM as it will see a possible pending exception and forward it
1657     // and never return here preventing us from clearing _last_native_pc down below.
1658     // Also can't use call_VM_leaf either as it will check to see if rsi & rdi are
1659     // preserved and correspond to the bcp/locals pointers. So we do a runtime call
1660     // by hand.
1661     //
1662     save_native_result(masm, ret_type, stack_slots);
1663     __ movq(c_rarg0, r15_thread);
1664     __ movq(r12, rsp); // remember sp
1665     __ subq(rsp, frame::arg_reg_save_area_bytes); // windows
1666     __ andq(rsp, -16); // align stack as required by ABI
1667     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans)));
1668     __ movq(rsp, r12); // restore sp
1669     // Restore any method result value
1670     restore_native_result(masm, ret_type, stack_slots);
1671     __ bind(Continue);
1672   }
1673 
1674   // change thread state
1675   __ movl(Address(r15_thread, JavaThread::thread_state_offset()), _thread_in_Java);
1676 
1677   Label reguard;
1678   Label reguard_done;
1679   __ cmpl(Address(r15_thread, JavaThread::stack_guard_state_offset()), JavaThread::stack_guard_yellow_disabled);
1680   __ jcc(Assembler::equal, reguard);
1681   __ bind(reguard_done);
1682 
1683   // native result if any is live 
1684 
1685   // Unlock
1686   Label unlock_done;
1687   Label slow_path_unlock;
1688   if (method->is_synchronized()) {
1689 
1690     // Get locked oop from the handle we passed to jni
1691     __ movq(obj_reg, Address(oop_handle_reg, 0));
1692 
1693     Label done;
1694 
1695     if (UseBiasedLocking) {
1696       __ biased_locking_exit(obj_reg, old_hdr, done);
1697     }
1698 
1699     // Simple recursive lock?
1700 
1701     __ cmpq(Address(rsp, lock_slot_offset * VMRegImpl::stack_slot_size), (int)NULL_WORD);
1702     __ jcc(Assembler::equal, done);
1703 
1704     // Must save rax if if it is live now because cmpxchg must use it
1705     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
1706       save_native_result(masm, ret_type, stack_slots);
1707     }
1708 
1709 
1710     // get address of the stack lock
1711     __ leaq(rax, Address(rsp, lock_slot_offset * VMRegImpl::stack_slot_size));
1712     //  get old displaced header
1713     __ movq(old_hdr, Address(rax, 0));
1714 
1715     // Atomic swap old header if oop still contains the stack lock
1716     if (os::is_MP()) {
1717       __ lock();
1718     }
1719     __ cmpxchgq(old_hdr, Address(obj_reg, 0));
1720     __ jcc(Assembler::notEqual, slow_path_unlock);
1721 
1722     // slow path re-enters here
1723     __ bind(unlock_done);
1724     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
1725       restore_native_result(masm, ret_type, stack_slots);
1726     }
1727 
1728     __ bind(done);
1729 
1730   }
1731 
1732   {
1733     SkipIfEqual skip(masm, &DTraceMethodProbes, false);
1734     save_native_result(masm, ret_type, stack_slots);
1735     __ movoop(c_rarg1, JNIHandles::make_local(method()));
1736     __ call_VM_leaf(
1737          CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit), 
1738          r15_thread, c_rarg1);
1739     restore_native_result(masm, ret_type, stack_slots);
1740   }
1741 
1742   __ reset_last_Java_frame(false, true);
1743 
1744   // Unpack oop result
1745   if (ret_type == T_OBJECT || ret_type == T_ARRAY) {
1746       Label L;
1747       __ testq(rax, rax);
1748       __ jcc(Assembler::zero, L);
1749       __ movq(rax, Address(rax, 0));
1750       __ bind(L);
1751       __ verify_oop(rax);
1752   }
1753 
1754   // reset handle block
1755   __ movq(rcx, Address(r15_thread, JavaThread::active_handles_offset()));
1756   __ movptr(Address(rcx, JNIHandleBlock::top_offset_in_bytes()), (int)NULL_WORD);
1757 
1758   // pop our frame
1759 
1760   __ leave();
1761 
1762   // Any exception pending?
1763   __ cmpq(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), (int)NULL_WORD);
1764   __ jcc(Assembler::notEqual, exception_pending);
1765 
1766   // Return
1767 
1768   __ ret(0);
1769 
1770   // Unexpected paths are out of line and go here
1771 
1772   // forward the exception
1773   __ bind(exception_pending);
1774 
1775   // and forward the exception
1776   __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
1777 
1778 
1779   // Slow path locking & unlocking
1780   if (method->is_synchronized()) {
1781 
1782     // BEGIN Slow path lock
1783     __ bind(slow_path_lock);
1784 
1785     // has last_Java_frame setup. No exceptions so do vanilla call not call_VM
1786     // args are (oop obj, BasicLock* lock, JavaThread* thread)
1787 
1788     // protect the args we've loaded
1789     save_args(masm, total_c_args, c_arg, out_regs);
1790 
1791     __ movq(c_rarg0, obj_reg);
1792     __ movq(c_rarg1, lock_reg);
1793     __ movq(c_rarg2, r15_thread);
1794 
1795     // Not a leaf but we have last_Java_frame setup as we want
1796     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_locking_C), 3);
1797     restore_args(masm, total_c_args, c_arg, out_regs);
1798 
1799 #ifdef ASSERT
1800     { Label L;
1801     __ cmpq(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), (int)NULL_WORD);
1802     __ jcc(Assembler::equal, L);
1803     __ stop("no pending exception allowed on exit from monitorenter");
1804     __ bind(L);
1805     }
1806 #endif
1807     __ jmp(lock_done);
1808 
1809     // END Slow path lock
1810 
1811     // BEGIN Slow path unlock
1812     __ bind(slow_path_unlock);
1813 
1814     // If we haven't already saved the native result we must save it now as xmm registers
1815     // are still exposed.
1816 
1817     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
1818       save_native_result(masm, ret_type, stack_slots);
1819     }
1820 
1821     __ leaq(c_rarg1, Address(rsp, lock_slot_offset * VMRegImpl::stack_slot_size));
1822 
1823     __ movq(c_rarg0, obj_reg);
1824     __ movq(r12, rsp); // remember sp
1825     __ subq(rsp, frame::arg_reg_save_area_bytes); // windows
1826     __ andq(rsp, -16); // align stack as required by ABI
1827 
1828     // Save pending exception around call to VM (which contains an EXCEPTION_MARK)
1829     // NOTE that obj_reg == rbx currently
1830     __ movq(rbx, Address(r15_thread, in_bytes(Thread::pending_exception_offset())));
1831     __ movptr(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), (int)NULL_WORD);
1832 
1833     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C)));
1834     __ movq(rsp, r12); // restore sp
1835 #ifdef ASSERT
1836     {
1837       Label L;
1838       __ cmpq(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), (int)NULL_WORD);
1839       __ jcc(Assembler::equal, L);
1840       __ stop("no pending exception allowed on exit complete_monitor_unlocking_C");
1841       __ bind(L);
1842     }
1843 #endif /* ASSERT */
1844 
1845     __ movq(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), rbx);
1846 
1847     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
1848       restore_native_result(masm, ret_type, stack_slots);
1849     }
1850     __ jmp(unlock_done);
1851 
1852     // END Slow path unlock
1853 
1854   } // synchronized 
1855   
1856   // SLOW PATH Reguard the stack if needed
1857 
1858   __ bind(reguard);
1859   save_native_result(masm, ret_type, stack_slots);
1860   __ movq(r12, rsp); // remember sp
1861   __ subq(rsp, frame::arg_reg_save_area_bytes); // windows
1862   __ andq(rsp, -16); // align stack as required by ABI
1863   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages)));
1864   __ movq(rsp, r12); // restore sp
1865   restore_native_result(masm, ret_type, stack_slots);
1866   // and continue
1867   __ jmp(reguard_done);
1868 
1869 
1870 
1871   __ flush();
1872 
1873   nmethod *nm = nmethod::new_native_nmethod(method,
1874                                             masm->code(),
1875                                             vep_offset,
1876                                             frame_complete,
1877                                             stack_slots / VMRegImpl::slots_per_word,
1878                                             (is_static ? in_ByteSize(klass_offset) : in_ByteSize(receiver_offset)),
1879                                             in_ByteSize(lock_slot_offset*VMRegImpl::stack_slot_size),
1880                                             oop_maps);
1881   return nm;
1882 
1883 }
1884 
1885 // this function returns the adjust size (in number of words) to a c2i adapter
1886 // activation for use during deoptimization
1887 int Deoptimization::last_frame_adjust(int callee_parameters, int callee_locals ) {
1888   return (callee_locals - callee_parameters) * Interpreter::stackElementWords();
1889 }
1890 
1891 
1892 uint SharedRuntime::out_preserve_stack_slots() {
1893   return 0;
1894 }
1895 
1896 
1897 //------------------------------generate_deopt_blob----------------------------
1898 void SharedRuntime::generate_deopt_blob() {
1899   // Allocate space for the code
1900   ResourceMark rm;
1901   // Setup code generation tools
1902   CodeBuffer buffer("deopt_blob", 2048, 1024);
1903   MacroAssembler* masm = new MacroAssembler(&buffer);
1904   int frame_size_in_words;
1905   OopMap* map = NULL;
1906   OopMapSet *oop_maps = new OopMapSet();
1907 
1908   // -------------
1909   // This code enters when returning to a de-optimized nmethod.  A return
1910   // address has been pushed on the the stack, and return values are in
1911   // registers. 
1912   // If we are doing a normal deopt then we were called from the patched 
1913   // nmethod from the point we returned to the nmethod. So the return
1914   // address on the stack is wrong by NativeCall::instruction_size
1915   // We will adjust the value so it looks like we have the original return
1916   // address on the stack (like when we eagerly deoptimized).
1917   // In the case of an exception pending when deoptimizing, we enter
1918   // with a return address on the stack that points after the call we patched
1919   // into the exception handler. We have the following register state from,
1920   // e.g., the forward exception stub (see stubGenerator_x86_64.cpp).
1921   //    rax: exception oop
1922   //    rbx: exception handler
1923   //    rdx: throwing pc
1924   // So in this case we simply jam rdx into the useless return address and
1925   // the stack looks just like we want.
1926   //
1927   // At this point we need to de-opt.  We save the argument return
1928   // registers.  We call the first C routine, fetch_unroll_info().  This
1929   // routine captures the return values and returns a structure which
1930   // describes the current frame size and the sizes of all replacement frames.
1931   // The current frame is compiled code and may contain many inlined
1932   // functions, each with their own JVM state.  We pop the current frame, then
1933   // push all the new frames.  Then we call the C routine unpack_frames() to
1934   // populate these frames.  Finally unpack_frames() returns us the new target
1935   // address.  Notice that callee-save registers are BLOWN here; they have
1936   // already been captured in the vframeArray at the time the return PC was
1937   // patched.
1938   address start = __ pc();
1939   Label cont;
1940 
1941   // Prolog for non exception case!
1942 
1943   // Save everything in sight.
1944   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
1945 
1946   // Normal deoptimization.  Save exec mode for unpack_frames.
1947   __ movl(r12, Deoptimization::Unpack_deopt); // callee-saved
1948   __ jmp(cont);
1949   
1950   int exception_offset = __ pc() - start;
1951 
1952   // Prolog for exception case
1953 
1954   // Push throwing pc as return address
1955   __ pushq(rdx);
1956 
1957   // Save everything in sight.
1958   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
1959 
1960   // Deopt during an exception.  Save exec mode for unpack_frames.
1961   __ movl(r12, Deoptimization::Unpack_exception); // callee-saved
1962 
1963   __ bind(cont);
1964 
1965   // Call C code.  Need thread and this frame, but NOT official VM entry
1966   // crud.  We cannot block on this call, no GC can happen.  
1967   //
1968   // UnrollBlock* fetch_unroll_info(JavaThread* thread)
1969 
1970   // fetch_unroll_info needs to call last_java_frame().
1971 
1972   __ set_last_Java_frame(noreg, noreg, NULL);
1973 #ifdef ASSERT
1974   { Label L;
1975     __ cmpq(Address(r15_thread,
1976                     JavaThread::last_Java_fp_offset()),
1977             0);
1978     __ jcc(Assembler::equal, L);
1979     __ stop("SharedRuntime::generate_deopt_blob: last_Java_fp not cleared");
1980     __ bind(L);
1981   }
1982 #endif // ASSERT
1983   __ movq(c_rarg0, r15_thread);
1984   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::fetch_unroll_info)));
1985 
1986   // Need to have an oopmap that tells fetch_unroll_info where to
1987   // find any register it might need.
1988   oop_maps->add_gc_map(__ pc() - start, map);
1989 
1990   __ reset_last_Java_frame(false, false);
1991 
1992   // Load UnrollBlock* into rdi
1993   __ movq(rdi, rax);
1994 
1995   // Only register save data is on the stack.
1996   // Now restore the result registers.  Everything else is either dead
1997   // or captured in the vframeArray.
1998   RegisterSaver::restore_result_registers(masm);
1999 
2000   // All of the register save area has been popped of the stack. Only the
2001   // return address remains.
2002 
2003   // Pop all the frames we must move/replace. 
2004   // 
2005   // Frame picture (youngest to oldest)
2006   // 1: self-frame (no frame link)
2007   // 2: deopting frame  (no frame link)
2008   // 3: caller of deopting frame (could be compiled/interpreted).
2009   // 
2010   // Note: by leaving the return address of self-frame on the stack
2011   // and using the size of frame 2 to adjust the stack
2012   // when we are done the return to frame 3 will still be on the stack.
2013 
2014   // Pop deoptimized frame
2015   __ movl(rcx, Address(rdi, Deoptimization::UnrollBlock::size_of_deoptimized_frame_offset_in_bytes()));
2016   __ addq(rsp, rcx);
2017 
2018   // rsp should be pointing at the return address to the caller (3)
2019 
2020   // Stack bang to make sure there's enough room for these interpreter frames.
2021   if (UseStackBanging) {
2022     __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes())); 
2023     __ bang_stack_size(rbx, rcx);
2024   }
2025 
2026   // Load address of array of frame pcs into rcx
2027   __ movq(rcx, Address(rdi, Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2028 
2029   // Trash the old pc
2030   __ addq(rsp, wordSize);
2031 
2032   // Load address of array of frame sizes into rsi
2033   __ movq(rsi, Address(rdi, Deoptimization::UnrollBlock::frame_sizes_offset_in_bytes()));
2034 
2035   // Load counter into rdx
2036   __ movl(rdx, Address(rdi, Deoptimization::UnrollBlock::number_of_frames_offset_in_bytes()));
2037 
2038   // Pick up the initial fp we should save
2039   __ movq(rbp, Address(rdi, Deoptimization::UnrollBlock::initial_fp_offset_in_bytes()));
2040 
2041   // Now adjust the caller's stack to make up for the extra locals
2042   // but record the original sp so that we can save it in the skeletal interpreter
2043   // frame and the stack walking of interpreter_sender will get the unextended sp
2044   // value and not the "real" sp value.
2045 
2046   const Register sender_sp = r8;
2047 
2048   __ movq(sender_sp, rsp);
2049   __ movl(rbx, Address(rdi,
2050                        Deoptimization::UnrollBlock::
2051                        caller_adjustment_offset_in_bytes()));
2052   __ subq(rsp, rbx);
2053 
2054   // Push interpreter frames in a loop
2055   Label loop;
2056   __ bind(loop);
2057   __ movq(rbx, Address(rsi, 0));        // Load frame size
2058   __ subq(rbx, 2*wordSize);             // We'll push pc and ebp by hand
2059   __ pushq(Address(rcx, 0));            // Save return address
2060   __ enter();                           // Save old & set new ebp
2061   __ subq(rsp, rbx);                    // Prolog
2062   __ movq(Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize),
2063           sender_sp);                   // Make it walkable
2064   // This value is corrected by layout_activation_impl 
2065   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), (int)NULL_WORD );
2066   __ movq(sender_sp, rsp);              // Pass sender_sp to next frame
2067   __ addq(rsi, wordSize);               // Bump array pointer (sizes)
2068   __ addq(rcx, wordSize);               // Bump array pointer (pcs)
2069   __ decrementl(rdx);                   // Decrement counter
2070   __ jcc(Assembler::notZero, loop);
2071   __ pushq(Address(rcx, 0));            // Save final return address
2072 
2073   // Re-push self-frame
2074   __ enter();                           // Save old & set new ebp
2075 
2076   // Allocate a full sized register save area.
2077   // Return address and rbp are in place, so we allocate two less words.
2078   __ subq(rsp, (frame_size_in_words - 2) * wordSize);
2079 
2080   // Restore frame locals after moving the frame
2081   __ movdbl(Address(rsp, RegisterSaver::xmm0_offset_in_bytes()), xmm0);
2082   __ movq(Address(rsp, RegisterSaver::rax_offset_in_bytes()), rax);
2083 
2084   // Call C code.  Need thread but NOT official VM entry
2085   // crud.  We cannot block on this call, no GC can happen.  Call should
2086   // restore return values to their stack-slots with the new SP.
2087   //
2088   // void Deoptimization::unpack_frames(JavaThread* thread, int exec_mode)
2089 
2090   // Use rbp because the frames look interpreted now
2091   __ set_last_Java_frame(noreg, rbp, NULL);
2092 
2093   __ movq(c_rarg0, r15_thread);
2094   __ movl(c_rarg1, r12); // second arg: exec_mode
2095   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2096 
2097   // Set an oopmap for the call site
2098   oop_maps->add_gc_map(__ pc() - start,
2099                        new OopMap( frame_size_in_words, 0 ));
2100 
2101   __ reset_last_Java_frame(true, false);
2102 
2103   // Collect return values
2104   __ movdbl(xmm0, Address(rsp, RegisterSaver::xmm0_offset_in_bytes()));
2105   __ movq(rax, Address(rsp, RegisterSaver::rax_offset_in_bytes()));
2106 
2107   // Pop self-frame.
2108   __ leave();                           // Epilog
2109 
2110   // Jump to interpreter
2111   __ ret(0);
2112   
2113   // Make sure all code is generated
2114   masm->flush();
2115 
2116   _deopt_blob = DeoptimizationBlob::create(&buffer, oop_maps, 0, exception_offset, 0, frame_size_in_words);
2117 }
2118 
2119 #ifdef COMPILER2
2120 //------------------------------generate_uncommon_trap_blob--------------------
2121 void SharedRuntime::generate_uncommon_trap_blob() {
2122   // Allocate space for the code
2123   ResourceMark rm;
2124   // Setup code generation tools
2125   CodeBuffer buffer("uncommon_trap_blob", 2048, 1024);
2126   MacroAssembler* masm = new MacroAssembler(&buffer);
2127 
2128   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
2129   
2130   address start = __ pc();
2131 
2132   // Push self-frame.  We get here with a return address on the
2133   // stack, so rsp is 8-byte aligned until we allocate our frame.
2134   __ subq(rsp, SimpleRuntimeFrame::return_off << LogBytesPerInt); // Epilog!
2135 
2136   // No callee saved registers. rbp is assumed implicitly saved
2137   __ movq(Address(rsp, SimpleRuntimeFrame::rbp_off << LogBytesPerInt), rbp);
2138 
2139   // compiler left unloaded_class_index in j_rarg0 move to where the
2140   // runtime expects it.
2141   __ movl(c_rarg1, j_rarg0);
2142 
2143   __ set_last_Java_frame(noreg, noreg, NULL);
2144 
2145   // Call C code.  Need thread but NOT official VM entry
2146   // crud.  We cannot block on this call, no GC can happen.  Call should
2147   // capture callee-saved registers as well as return values.
2148   // Thread is in rdi already.
2149   //
2150   // UnrollBlock* uncommon_trap(JavaThread* thread, jint unloaded_class_index);
2151 
2152   __ movq(c_rarg0, r15_thread);
2153   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::uncommon_trap)));
2154 
2155   // Set an oopmap for the call site
2156   OopMapSet* oop_maps = new OopMapSet();
2157   OopMap* map = new OopMap(SimpleRuntimeFrame::framesize, 0);
2158 
2159   // location of rbp is known implicitly by the frame sender code
2160 
2161   oop_maps->add_gc_map(__ pc() - start, map);
2162 
2163   __ reset_last_Java_frame(false, false);
2164 
2165   // Load UnrollBlock* into rdi
2166   __ movq(rdi, rax);
2167 
2168   // Pop all the frames we must move/replace. 
2169   // 
2170   // Frame picture (youngest to oldest)
2171   // 1: self-frame (no frame link)
2172   // 2: deopting frame  (no frame link)
2173   // 3: caller of deopting frame (could be compiled/interpreted).
2174 
2175   // Pop self-frame.  We have no frame, and must rely only on rax and rsp.
2176   __ addq(rsp, (SimpleRuntimeFrame::framesize - 2) << LogBytesPerInt); // Epilog!
2177 
2178   // Pop deoptimized frame (int)
2179   __ movl(rcx, Address(rdi,
2180                        Deoptimization::UnrollBlock::
2181                        size_of_deoptimized_frame_offset_in_bytes()));
2182   __ addq(rsp, rcx);
2183 
2184   // rsp should be pointing at the return address to the caller (3)
2185 
2186   // Stack bang to make sure there's enough room for these interpreter frames.
2187   if (UseStackBanging) {
2188     __ movl(rbx, Address(rdi ,Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes())); 
2189     __ bang_stack_size(rbx, rcx);
2190   }
2191 
2192   // Load address of array of frame pcs into rcx (address*)
2193   __ movq(rcx, 
2194           Address(rdi,
2195                   Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2196 
2197   // Trash the return pc
2198   __ addq(rsp, wordSize);
2199 
2200   // Load address of array of frame sizes into rsi (intptr_t*)
2201   __ movq(rsi, Address(rdi,
2202                        Deoptimization::UnrollBlock::
2203                        frame_sizes_offset_in_bytes()));
2204 
2205   // Counter
2206   __ movl(rdx, Address(rdi, 
2207                        Deoptimization::UnrollBlock::
2208                        number_of_frames_offset_in_bytes())); // (int)
2209 
2210   // Pick up the initial fp we should save
2211   __ movq(rbp, 
2212           Address(rdi, 
2213                   Deoptimization::UnrollBlock::initial_fp_offset_in_bytes()));
2214 
2215   // Now adjust the caller's stack to make up for the extra locals but
2216   // record the original sp so that we can save it in the skeletal
2217   // interpreter frame and the stack walking of interpreter_sender
2218   // will get the unextended sp value and not the "real" sp value.
2219 
2220   const Register sender_sp = r8;
2221 
2222   __ movq(sender_sp, rsp);
2223   __ movl(rbx, Address(rdi, 
2224                        Deoptimization::UnrollBlock::
2225                        caller_adjustment_offset_in_bytes())); // (int)
2226   __ subq(rsp, rbx);
2227 
2228   // Push interpreter frames in a loop
2229   Label loop;
2230   __ bind(loop);
2231   __ movq(rbx, Address(rsi, 0)); // Load frame size
2232   __ subq(rbx, 2 * wordSize); // We'll push pc and rbp by hand
2233   __ pushq(Address(rcx, 0));  // Save return address
2234   __ enter();                 // Save old & set new rbp
2235   __ subq(rsp, rbx);          // Prolog
2236   __ movq(Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize),
2237           sender_sp);         // Make it walkable
2238   // This value is corrected by layout_activation_impl 
2239   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), (int)NULL_WORD );
2240   __ movq(sender_sp, rsp);    // Pass sender_sp to next frame
2241   __ addq(rsi, wordSize);     // Bump array pointer (sizes)
2242   __ addq(rcx, wordSize);     // Bump array pointer (pcs)
2243   __ decrementl(rdx);         // Decrement counter
2244   __ jcc(Assembler::notZero, loop);
2245   __ pushq(Address(rcx, 0)); // Save final return address
2246 
2247   // Re-push self-frame
2248   __ enter();                 // Save old & set new rbp
2249   __ subq(rsp, (SimpleRuntimeFrame::framesize - 4) << LogBytesPerInt); 
2250                               // Prolog
2251 
2252   // Use rbp because the frames look interpreted now
2253   __ set_last_Java_frame(noreg, rbp, NULL);
2254 
2255   // Call C code.  Need thread but NOT official VM entry
2256   // crud.  We cannot block on this call, no GC can happen.  Call should
2257   // restore return values to their stack-slots with the new SP.
2258   // Thread is in rdi already.
2259   //
2260   // BasicType unpack_frames(JavaThread* thread, int exec_mode);
2261 
2262   __ movq(c_rarg0, r15_thread);
2263   __ movl(c_rarg1, Deoptimization::Unpack_uncommon_trap);
2264   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2265 
2266   // Set an oopmap for the call site
2267   oop_maps->add_gc_map(__ pc() - start, new OopMap(SimpleRuntimeFrame::framesize, 0));
2268 
2269   __ reset_last_Java_frame(true, false);
2270 
2271   // Pop self-frame.
2272   __ leave();                 // Epilog
2273 
2274   // Jump to interpreter
2275   __ ret(0);
2276 
2277   // Make sure all code is generated
2278   masm->flush();
2279 
2280   _uncommon_trap_blob =  UncommonTrapBlob::create(&buffer, oop_maps, 
2281                                                  SimpleRuntimeFrame::framesize >> 1);
2282 }
2283 #endif // COMPILER2
2284 
2285 
2286 //------------------------------generate_handler_blob------
2287 //
2288 // Generate a special Compile2Runtime blob that saves all registers, 
2289 // and setup oopmap.
2290 //
2291 static SafepointBlob* generate_handler_blob(address call_ptr, bool cause_return) {
2292   assert(StubRoutines::forward_exception_entry() != NULL,
2293          "must be generated before");  
2294 
2295   ResourceMark rm;
2296   OopMapSet *oop_maps = new OopMapSet();
2297   OopMap* map;
2298 
2299   // Allocate space for the code.  Setup code generation tools.
2300   CodeBuffer buffer("handler_blob", 2048, 1024);
2301   MacroAssembler* masm = new MacroAssembler(&buffer);
2302   
2303   address start   = __ pc();  
2304   address call_pc = NULL;  
2305   int frame_size_in_words;
2306 
2307   // Make room for return address (or push it again)
2308   if (!cause_return) {
2309     __ pushq(rbx);
2310   }
2311 
2312   // Save registers, fpu state, and flags  
2313   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
2314   
2315   // The following is basically a call_VM.  However, we need the precise
2316   // address of the call in order to generate an oopmap. Hence, we do all the
2317   // work outselves.
2318 
2319   __ set_last_Java_frame(noreg, noreg, NULL);
2320 
2321   // The return address must always be correct so that frame constructor never
2322   // sees an invalid pc.
2323 
2324   if (!cause_return) {
2325     // overwrite the dummy value we pushed on entry 
2326     __ movq(c_rarg0, Address(r15_thread, JavaThread::saved_exception_pc_offset()));
2327     __ movq(Address(rbp, wordSize), c_rarg0);
2328   }
2329 
2330   // Do the call
2331   __ movq(c_rarg0, r15_thread);
2332   __ call(RuntimeAddress(call_ptr));
2333 
2334   // Set an oopmap for the call site.  This oopmap will map all
2335   // oop-registers and debug-info registers as callee-saved.  This
2336   // will allow deoptimization at this safepoint to find all possible
2337   // debug-info recordings, as well as let GC find all oops.
2338 
2339   oop_maps->add_gc_map( __ pc() - start, map);
2340 
2341   Label noException;
2342 
2343   __ reset_last_Java_frame(false, false);
2344 
2345   __ cmpq(Address(r15_thread, Thread::pending_exception_offset()), (int)NULL_WORD);
2346   __ jcc(Assembler::equal, noException);
2347 
2348   // Exception pending
2349 
2350   RegisterSaver::restore_live_registers(masm);
2351 
2352   __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2353 
2354   // No exception case
2355   __ bind(noException);
2356 
2357   // Normal exit, restore registers and exit.
2358   RegisterSaver::restore_live_registers(masm);
2359 
2360   __ ret(0);
2361 
2362   // Make sure all code is generated
2363   masm->flush();  
2364 
2365   // Fill-out other meta info
2366   return SafepointBlob::create(&buffer, oop_maps, frame_size_in_words);    
2367 }
2368 
2369 //
2370 // generate_resolve_blob - call resolution (static/virtual/opt-virtual/ic-miss
2371 // 
2372 // Generate a stub that calls into vm to find out the proper destination
2373 // of a java call. All the argument registers are live at this point
2374 // but since this is generic code we don't know what they are and the caller
2375 // must do any gc of the args.
2376 //
2377 static RuntimeStub* generate_resolve_blob(address destination, const char* name) {
2378   assert (StubRoutines::forward_exception_entry() != NULL, "must be generated before");  
2379 
2380   // allocate space for the code
2381   ResourceMark rm;
2382 
2383   CodeBuffer buffer(name, 1000, 512);
2384   MacroAssembler* masm                = new MacroAssembler(&buffer);
2385 
2386   int frame_size_in_words;
2387   
2388   OopMapSet *oop_maps = new OopMapSet();
2389   OopMap* map = NULL;
2390   
2391   int start = __ offset();
2392 
2393   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
2394 
2395   int frame_complete = __ offset();
2396 
2397   __ set_last_Java_frame(noreg, noreg, NULL);
2398 
2399   __ movq(c_rarg0, r15_thread);
2400 
2401   __ call(RuntimeAddress(destination));
2402 
2403 
2404   // Set an oopmap for the call site.
2405   // We need this not only for callee-saved registers, but also for volatile
2406   // registers that the compiler might be keeping live across a safepoint.
2407 
2408   oop_maps->add_gc_map( __ offset() - start, map);
2409 
2410   // rax contains the address we are going to jump to assuming no exception got installed
2411 
2412   // clear last_Java_sp
2413   __ reset_last_Java_frame(false, false);
2414   // check for pending exceptions
2415   Label pending;
2416   __ cmpq(Address(r15_thread, Thread::pending_exception_offset()), (int)NULL_WORD);
2417   __ jcc(Assembler::notEqual, pending);
2418 
2419   // get the returned methodOop
2420   __ movq(rbx, Address(r15_thread, JavaThread::vm_result_offset()));
2421   __ movq(Address(rsp, RegisterSaver::rbx_offset_in_bytes()), rbx);
2422 
2423   __ movq(Address(rsp, RegisterSaver::rax_offset_in_bytes()), rax);
2424 
2425   RegisterSaver::restore_live_registers(masm);
2426 
2427   // We are back the the original state on entry and ready to go.
2428 
2429   __ jmp(rax);
2430 
2431   // Pending exception after the safepoint
2432 
2433   __ bind(pending);
2434 
2435   RegisterSaver::restore_live_registers(masm);
2436 
2437   // exception pending => remove activation and forward to exception handler
2438 
2439   __ movptr(Address(r15_thread, JavaThread::vm_result_offset()), (int)NULL_WORD);
2440 
2441   __ movq(rax, Address(r15_thread, Thread::pending_exception_offset()));
2442   __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2443 
2444   // -------------
2445   // make sure all code is generated
2446   masm->flush();  
2447 
2448   // return the  blob
2449   // frame_size_words or bytes??
2450   return RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, frame_size_in_words, oop_maps, true);
2451 }
2452 
2453 
2454 void SharedRuntime::generate_stubs() {
2455 
2456   _wrong_method_blob = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method),
2457                                         "wrong_method_stub");
2458   _ic_miss_blob =      generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_ic_miss),
2459                                         "ic_miss_stub");
2460   _resolve_opt_virtual_call_blob = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_opt_virtual_call_C),
2461                                         "resolve_opt_virtual_call");
2462 
2463   _resolve_virtual_call_blob = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_virtual_call_C),
2464                                         "resolve_virtual_call");
2465 
2466   _resolve_static_call_blob = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_static_call_C),
2467                                         "resolve_static_call");
2468   _polling_page_safepoint_handler_blob =
2469     generate_handler_blob(CAST_FROM_FN_PTR(address, 
2470                    SafepointSynchronize::handle_polling_page_exception), false);
2471 
2472   _polling_page_return_handler_blob =
2473     generate_handler_blob(CAST_FROM_FN_PTR(address,
2474                    SafepointSynchronize::handle_polling_page_exception), true);
2475                   
2476   generate_deopt_blob();
2477 
2478 #ifdef COMPILER2
2479   generate_uncommon_trap_blob();
2480 #endif // COMPILER2
2481 }
2482 
2483 
2484 #ifdef COMPILER2
2485 // This is here instead of runtime_x86_64.cpp because it uses SimpleRuntimeFrame
2486 //
2487 //------------------------------generate_exception_blob---------------------------
2488 // creates exception blob at the end
2489 // Using exception blob, this code is jumped from a compiled method.
2490 // (see emit_exception_handler in x86_64.ad file)
2491 // 
2492 // Given an exception pc at a call we call into the runtime for the
2493 // handler in this method. This handler might merely restore state
2494 // (i.e. callee save registers) unwind the frame and jump to the
2495 // exception handler for the nmethod if there is no Java level handler
2496 // for the nmethod.
2497 //
2498 // This code is entered with a jmp.
2499 // 
2500 // Arguments:
2501 //   rax: exception oop
2502 //   rdx: exception pc
2503 //
2504 // Results:
2505 //   rax: exception oop
2506 //   rdx: exception pc in caller or ???
2507 //   destination: exception handler of caller
2508 // 
2509 // Note: the exception pc MUST be at a call (precise debug information)
2510 //       Registers rax, rdx, rcx, rsi, rdi, r8-r11 are not callee saved.
2511 //
2512 
2513 void OptoRuntime::generate_exception_blob() {
2514   assert(!OptoRuntime::is_callee_saved_register(RDX_num), "");
2515   assert(!OptoRuntime::is_callee_saved_register(RAX_num), "");
2516   assert(!OptoRuntime::is_callee_saved_register(RCX_num), "");
2517 
2518   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
2519 
2520   // Allocate space for the code
2521   ResourceMark rm;
2522   // Setup code generation tools  
2523   CodeBuffer buffer("exception_blob", 2048, 1024);
2524   MacroAssembler* masm = new MacroAssembler(&buffer);
2525 
2526 
2527   address start = __ pc();  
2528 
2529   // Exception pc is 'return address' for stack walker
2530   __ pushq(rdx);
2531   __ subq(rsp, SimpleRuntimeFrame::return_off << LogBytesPerInt); // Prolog
2532 
2533   // Save callee-saved registers.  See x86_64.ad.
2534 
2535   // rbp is an implicitly saved callee saved register (i.e. the calling
2536   // convention will save restore it in prolog/epilog) Other than that
2537   // there are no callee save registers now that adapter frames are gone.
2538 
2539   __ movq(Address(rsp, SimpleRuntimeFrame::rbp_off << LogBytesPerInt), rbp);
2540           
2541   // Store exception in Thread object. We cannot pass any arguments to the
2542   // handle_exception call, since we do not want to make any assumption
2543   // about the size of the frame where the exception happened in.
2544   // c_rarg0 is either rdi (Linux) or rcx (Windows).
2545   __ movq(Address(r15_thread, JavaThread::exception_oop_offset()),rax);
2546   __ movq(Address(r15_thread, JavaThread::exception_pc_offset()), rdx);
2547 
2548   // This call does all the hard work.  It checks if an exception handler
2549   // exists in the method.  
2550   // If so, it returns the handler address.
2551   // If not, it prepares for stack-unwinding, restoring the callee-save 
2552   // registers of the frame being removed.
2553   //
2554   // address OptoRuntime::handle_exception_C(JavaThread* thread)
2555 
2556   __ set_last_Java_frame(noreg, noreg, NULL);
2557   __ movq(c_rarg0, r15_thread);
2558   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, OptoRuntime::handle_exception_C)));
2559 
2560   // Set an oopmap for the call site.  This oopmap will only be used if we
2561   // are unwinding the stack.  Hence, all locations will be dead.
2562   // Callee-saved registers will be the same as the frame above (i.e.,
2563   // handle_exception_stub), since they were restored when we got the
2564   // exception.
2565 
2566   OopMapSet* oop_maps = new OopMapSet();
2567 
2568   oop_maps->add_gc_map( __ pc()-start, new OopMap(SimpleRuntimeFrame::framesize, 0));
2569 
2570   __ reset_last_Java_frame(false, false);
2571 
2572   // Restore callee-saved registers
2573 
2574   // rbp is an implicitly saved callee saved register (i.e. the calling
2575   // convention will save restore it in prolog/epilog) Other than that
2576   // there are no callee save registers no that adapter frames are gone.
2577 
2578   __ movq(rbp, Address(rsp, SimpleRuntimeFrame::rbp_off << LogBytesPerInt));
2579 
2580   __ addq(rsp, SimpleRuntimeFrame::return_off << LogBytesPerInt); // Epilog
2581   __ popq(rdx);                  // No need for exception pc anymore
2582 
2583   // rax: exception handler
2584 
2585   // We have a handler in rax (could be deopt blob).
2586   __ movq(r8, rax);
2587 
2588   // Get the exception oop
2589   __ movq(rax, Address(r15_thread, JavaThread::exception_oop_offset()));
2590   // Get the exception pc in case we are deoptimized
2591   __ movq(rdx, Address(r15_thread, JavaThread::exception_pc_offset()));
2592 #ifdef ASSERT
2593   __ movptr(Address(r15_thread, JavaThread::exception_handler_pc_offset()), (int)NULL_WORD);
2594   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), (int)NULL_WORD); 
2595 #endif
2596   // Clear the exception oop so GC no longer processes it as a root.
2597   __ movptr(Address(r15_thread, JavaThread::exception_oop_offset()), (int)NULL_WORD);
2598 
2599   // rax: exception oop
2600   // r8:  exception handler
2601   // rdx: exception pc
2602   // Jump to handler
2603 
2604   __ jmp(r8);
2605 
2606   // Make sure all code is generated
2607   masm->flush();  
2608 
2609   // Set exception blob
2610   _exception_blob =  ExceptionBlob::create(&buffer, oop_maps, SimpleRuntimeFrame::framesize >> 1);
2611 }
2612 #endif // COMPILER2