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