1 /*
   2  * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2014, 2021, Red Hat Inc. All rights reserved.
   4  * Copyright (c) 2021, Azul Systems, Inc. All rights reserved.
   5  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   6  *
   7  * This code is free software; you can redistribute it and/or modify it
   8  * under the terms of the GNU General Public License version 2 only, as
   9  * published by the Free Software Foundation.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  *
  25  */
  26 
  27 #include "precompiled.hpp"
  28 #include "asm/macroAssembler.hpp"
  29 #include "asm/macroAssembler.inline.hpp"
  30 #include "code/codeCache.hpp"
  31 #include "code/compiledIC.hpp"
  32 #include "code/debugInfoRec.hpp"
  33 #include "code/icBuffer.hpp"
  34 #include "code/vtableStubs.hpp"
  35 #include "compiler/oopMap.hpp"
  36 #include "gc/shared/barrierSetAssembler.hpp"
  37 #include "interpreter/interpreter.hpp"
  38 #include "interpreter/interp_masm.hpp"
  39 #include "logging/log.hpp"
  40 #include "memory/resourceArea.hpp"
  41 #include "nativeInst_aarch64.hpp"
  42 #include "oops/compiledICHolder.hpp"
  43 #include "oops/klass.inline.hpp"
  44 #include "prims/methodHandles.hpp"
  45 #include "runtime/jniHandles.hpp"
  46 #include "runtime/safepointMechanism.hpp"
  47 #include "runtime/sharedRuntime.hpp"
  48 #include "runtime/signature.hpp"
  49 #include "runtime/stubRoutines.hpp"
  50 #include "runtime/vframeArray.hpp"
  51 #include "utilities/align.hpp"
  52 #include "utilities/formatBuffer.hpp"
  53 #include "vmreg_aarch64.inline.hpp"
  54 #ifdef COMPILER1
  55 #include "c1/c1_Runtime1.hpp"
  56 #endif
  57 #ifdef COMPILER2
  58 #include "adfiles/ad_aarch64.hpp"
  59 #include "opto/runtime.hpp"
  60 #endif
  61 #if INCLUDE_JVMCI
  62 #include "jvmci/jvmciJavaClasses.hpp"
  63 #endif
  64 
  65 #define __ masm->
  66 
  67 const int StackAlignmentInSlots = StackAlignmentInBytes / VMRegImpl::stack_slot_size;
  68 
  69 class SimpleRuntimeFrame {
  70 
  71   public:
  72 
  73   // Most of the runtime stubs have this simple frame layout.
  74   // This class exists to make the layout shared in one place.
  75   // Offsets are for compiler stack slots, which are jints.
  76   enum layout {
  77     // The frame sender code expects that rbp will be in the "natural" place and
  78     // will override any oopMap setting for it. We must therefore force the layout
  79     // so that it agrees with the frame sender code.
  80     // we don't expect any arg reg save area so aarch64 asserts that
  81     // frame::arg_reg_save_area_bytes == 0
  82     rbp_off = 0,
  83     rbp_off2,
  84     return_off, return_off2,
  85     framesize
  86   };
  87 };
  88 
  89 // FIXME -- this is used by C1
  90 class RegisterSaver {
  91   const bool _save_vectors;
  92  public:
  93   RegisterSaver(bool save_vectors) : _save_vectors(save_vectors) {}
  94 
  95   OopMap* save_live_registers(MacroAssembler* masm, int additional_frame_words, int* total_frame_words);
  96   void restore_live_registers(MacroAssembler* masm);
  97 
  98   // Offsets into the register save area
  99   // Used by deoptimization when it is managing result register
 100   // values on its own
 101 
 102   int reg_offset_in_bytes(Register r);
 103   int r0_offset_in_bytes()    { return reg_offset_in_bytes(r0); }
 104   int rscratch1_offset_in_bytes()    { return reg_offset_in_bytes(rscratch1); }
 105   int v0_offset_in_bytes();
 106 
 107   // Total stack size in bytes for saving sve predicate registers.
 108   int total_sve_predicate_in_bytes();
 109 
 110   // Capture info about frame layout
 111   // Note this is only correct when not saving full vectors.
 112   enum layout {
 113                 fpu_state_off = 0,
 114                 fpu_state_end = fpu_state_off + FPUStateSizeInWords - 1,
 115                 // The frame sender code expects that rfp will be in
 116                 // the "natural" place and will override any oopMap
 117                 // setting for it. We must therefore force the layout
 118                 // so that it agrees with the frame sender code.
 119                 r0_off = fpu_state_off + FPUStateSizeInWords,
 120                 rfp_off = r0_off + (RegisterImpl::number_of_registers - 2) * RegisterImpl::max_slots_per_register,
 121                 return_off = rfp_off + RegisterImpl::max_slots_per_register,      // slot for return address
 122                 reg_save_size = return_off + RegisterImpl::max_slots_per_register};
 123 
 124 };
 125 
 126 int RegisterSaver::reg_offset_in_bytes(Register r) {
 127   // The integer registers are located above the floating point
 128   // registers in the stack frame pushed by save_live_registers() so the
 129   // offset depends on whether we are saving full vectors, and whether
 130   // those vectors are NEON or SVE.
 131 
 132   int slots_per_vect = FloatRegisterImpl::save_slots_per_register;
 133 
 134 #if COMPILER2_OR_JVMCI
 135   if (_save_vectors) {
 136     slots_per_vect = FloatRegisterImpl::slots_per_neon_register;
 137 
 138 #ifdef COMPILER2
 139     if (Matcher::supports_scalable_vector()) {
 140       slots_per_vect = Matcher::scalable_vector_reg_size(T_FLOAT);
 141     }
 142 #endif
 143   }
 144 #endif
 145 
 146   int r0_offset = v0_offset_in_bytes() + (slots_per_vect * FloatRegisterImpl::number_of_registers) * BytesPerInt;
 147   return r0_offset + r->encoding() * wordSize;
 148 }
 149 
 150 int RegisterSaver::v0_offset_in_bytes() {
 151   // The floating point registers are located above the predicate registers if
 152   // they are present in the stack frame pushed by save_live_registers(). So the
 153   // offset depends on the saved total predicate vectors in the stack frame.
 154   return (total_sve_predicate_in_bytes() / VMRegImpl::stack_slot_size) * BytesPerInt;
 155 }
 156 
 157 int RegisterSaver::total_sve_predicate_in_bytes() {
 158 #ifdef COMPILER2
 159   if (_save_vectors && Matcher::supports_scalable_vector()) {
 160     // The number of total predicate bytes is unlikely to be a multiple
 161     // of 16 bytes so we manually align it up.
 162     return align_up(Matcher::scalable_predicate_reg_slots() *
 163                     VMRegImpl::stack_slot_size *
 164                     PRegisterImpl::number_of_saved_registers, 16);
 165   }
 166 #endif
 167   return 0;
 168 }
 169 
 170 OopMap* RegisterSaver::save_live_registers(MacroAssembler* masm, int additional_frame_words, int* total_frame_words) {
 171   bool use_sve = false;
 172   int sve_vector_size_in_bytes = 0;
 173   int sve_vector_size_in_slots = 0;
 174   int sve_predicate_size_in_slots = 0;
 175   int total_predicate_in_bytes = total_sve_predicate_in_bytes();
 176   int total_predicate_in_slots = total_predicate_in_bytes / VMRegImpl::stack_slot_size;
 177 
 178 #ifdef COMPILER2
 179   use_sve = Matcher::supports_scalable_vector();
 180   if (use_sve) {
 181     sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
 182     sve_vector_size_in_slots = Matcher::scalable_vector_reg_size(T_FLOAT);
 183     sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
 184   }
 185 #endif
 186 
 187 #if COMPILER2_OR_JVMCI
 188   if (_save_vectors) {
 189     int extra_save_slots_per_register = 0;
 190     // Save upper half of vector registers
 191     if (use_sve) {
 192       extra_save_slots_per_register = sve_vector_size_in_slots - FloatRegisterImpl::save_slots_per_register;
 193     } else {
 194       extra_save_slots_per_register = FloatRegisterImpl::extra_save_slots_per_neon_register;
 195     }
 196     int extra_vector_bytes = extra_save_slots_per_register *
 197                              VMRegImpl::stack_slot_size *
 198                              FloatRegisterImpl::number_of_registers;
 199     additional_frame_words += ((extra_vector_bytes + total_predicate_in_bytes) / wordSize);
 200   }
 201 #else
 202   assert(!_save_vectors, "vectors are generated only by C2 and JVMCI");
 203 #endif
 204 
 205   int frame_size_in_bytes = align_up(additional_frame_words * wordSize +
 206                                      reg_save_size * BytesPerInt, 16);
 207   // OopMap frame size is in compiler stack slots (jint's) not bytes or words
 208   int frame_size_in_slots = frame_size_in_bytes / BytesPerInt;
 209   // The caller will allocate additional_frame_words
 210   int additional_frame_slots = additional_frame_words * wordSize / BytesPerInt;
 211   // CodeBlob frame size is in words.
 212   int frame_size_in_words = frame_size_in_bytes / wordSize;
 213   *total_frame_words = frame_size_in_words;
 214 
 215   // Save Integer and Float registers.
 216   __ enter();
 217   __ push_CPU_state(_save_vectors, use_sve, sve_vector_size_in_bytes, total_predicate_in_bytes);
 218 
 219   // Set an oopmap for the call site.  This oopmap will map all
 220   // oop-registers and debug-info registers as callee-saved.  This
 221   // will allow deoptimization at this safepoint to find all possible
 222   // debug-info recordings, as well as let GC find all oops.
 223 
 224   OopMapSet *oop_maps = new OopMapSet();
 225   OopMap* oop_map = new OopMap(frame_size_in_slots, 0);
 226 
 227   for (int i = 0; i < RegisterImpl::number_of_registers; i++) {
 228     Register r = as_Register(i);
 229     if (r <= rfp && r != rscratch1 && r != rscratch2) {
 230       // SP offsets are in 4-byte words.
 231       // Register slots are 8 bytes wide, 32 floating-point registers.
 232       int sp_offset = RegisterImpl::max_slots_per_register * i +
 233                       FloatRegisterImpl::save_slots_per_register * FloatRegisterImpl::number_of_registers;
 234       oop_map->set_callee_saved(VMRegImpl::stack2reg(sp_offset + additional_frame_slots), r->as_VMReg());
 235     }
 236   }
 237 
 238   for (int i = 0; i < FloatRegisterImpl::number_of_registers; i++) {
 239     FloatRegister r = as_FloatRegister(i);
 240     int sp_offset = 0;
 241     if (_save_vectors) {
 242       sp_offset = use_sve ? (total_predicate_in_slots + sve_vector_size_in_slots * i) :
 243                             (FloatRegisterImpl::slots_per_neon_register * i);
 244     } else {
 245       sp_offset = FloatRegisterImpl::save_slots_per_register * i;
 246     }
 247     oop_map->set_callee_saved(VMRegImpl::stack2reg(sp_offset), r->as_VMReg());
 248   }
 249 
 250   if (_save_vectors && use_sve) {
 251     for (int i = 0; i < PRegisterImpl::number_of_saved_registers; i++) {
 252       PRegister r = as_PRegister(i);
 253       int sp_offset = sve_predicate_size_in_slots * i;
 254       oop_map->set_callee_saved(VMRegImpl::stack2reg(sp_offset), r->as_VMReg());
 255     }
 256   }
 257 
 258   return oop_map;
 259 }
 260 
 261 void RegisterSaver::restore_live_registers(MacroAssembler* masm) {
 262 #ifdef COMPILER2
 263   __ pop_CPU_state(_save_vectors, Matcher::supports_scalable_vector(),
 264                    Matcher::scalable_vector_reg_size(T_BYTE), total_sve_predicate_in_bytes());
 265 #else
 266 #if !INCLUDE_JVMCI
 267   assert(!_save_vectors, "vectors are generated only by C2 and JVMCI");
 268 #endif
 269   __ pop_CPU_state(_save_vectors);
 270 #endif
 271   __ ldp(rfp, lr, Address(__ post(sp, 2 * wordSize)));
 272 
 273 }
 274 
 275 // Is vector's size (in bytes) bigger than a size saved by default?
 276 // 8 bytes vector registers are saved by default on AArch64.
 277 // The SVE supported min vector size is 8 bytes and we need to save
 278 // predicate registers when the vector size is 8 bytes as well.
 279 bool SharedRuntime::is_wide_vector(int size) {
 280   return size > 8 || (UseSVE > 0 && size >= 8);
 281 }
 282 
 283 // The java_calling_convention describes stack locations as ideal slots on
 284 // a frame with no abi restrictions. Since we must observe abi restrictions
 285 // (like the placement of the register window) the slots must be biased by
 286 // the following value.
 287 static int reg2offset_in(VMReg r) {
 288   // Account for saved rfp and lr
 289   // This should really be in_preserve_stack_slots
 290   return (r->reg2stack() + 4) * VMRegImpl::stack_slot_size;
 291 }
 292 
 293 static int reg2offset_out(VMReg r) {
 294   return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
 295 }
 296 
 297 // ---------------------------------------------------------------------------
 298 // Read the array of BasicTypes from a signature, and compute where the
 299 // arguments should go.  Values in the VMRegPair regs array refer to 4-byte
 300 // quantities.  Values less than VMRegImpl::stack0 are registers, those above
 301 // refer to 4-byte stack slots.  All stack slots are based off of the stack pointer
 302 // as framesizes are fixed.
 303 // VMRegImpl::stack0 refers to the first slot 0(sp).
 304 // and VMRegImpl::stack0+1 refers to the memory word 4-byes higher.  Register
 305 // up to RegisterImpl::number_of_registers) are the 64-bit
 306 // integer registers.
 307 
 308 // Note: the INPUTS in sig_bt are in units of Java argument words,
 309 // which are 64-bit.  The OUTPUTS are in 32-bit units.
 310 
 311 // The Java calling convention is a "shifted" version of the C ABI.
 312 // By skipping the first C ABI register we can call non-static jni
 313 // methods with small numbers of arguments without having to shuffle
 314 // the arguments at all. Since we control the java ABI we ought to at
 315 // least get some advantage out of it.
 316 
 317 int SharedRuntime::java_calling_convention(const BasicType *sig_bt,
 318                                            VMRegPair *regs,
 319                                            int total_args_passed) {
 320 
 321   // Create the mapping between argument positions and
 322   // registers.
 323   static const Register INT_ArgReg[Argument::n_int_register_parameters_j] = {
 324     j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5, j_rarg6, j_rarg7
 325   };
 326   static const FloatRegister FP_ArgReg[Argument::n_float_register_parameters_j] = {
 327     j_farg0, j_farg1, j_farg2, j_farg3,
 328     j_farg4, j_farg5, j_farg6, j_farg7
 329   };
 330 
 331 
 332   uint int_args = 0;
 333   uint fp_args = 0;
 334   uint stk_args = 0; // inc by 2 each time
 335 
 336   for (int i = 0; i < total_args_passed; i++) {
 337     switch (sig_bt[i]) {
 338     case T_BOOLEAN:
 339     case T_CHAR:
 340     case T_BYTE:
 341     case T_SHORT:
 342     case T_INT:
 343       if (int_args < Argument::n_int_register_parameters_j) {
 344         regs[i].set1(INT_ArgReg[int_args++]->as_VMReg());
 345       } else {
 346         regs[i].set1(VMRegImpl::stack2reg(stk_args));
 347         stk_args += 2;
 348       }
 349       break;
 350     case T_VOID:
 351       // halves of T_LONG or T_DOUBLE
 352       assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
 353       regs[i].set_bad();
 354       break;
 355     case T_LONG:
 356       assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
 357       // fall through
 358     case T_OBJECT:
 359     case T_ARRAY:
 360     case T_ADDRESS:
 361       if (int_args < Argument::n_int_register_parameters_j) {
 362         regs[i].set2(INT_ArgReg[int_args++]->as_VMReg());
 363       } else {
 364         regs[i].set2(VMRegImpl::stack2reg(stk_args));
 365         stk_args += 2;
 366       }
 367       break;
 368     case T_FLOAT:
 369       if (fp_args < Argument::n_float_register_parameters_j) {
 370         regs[i].set1(FP_ArgReg[fp_args++]->as_VMReg());
 371       } else {
 372         regs[i].set1(VMRegImpl::stack2reg(stk_args));
 373         stk_args += 2;
 374       }
 375       break;
 376     case T_DOUBLE:
 377       assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
 378       if (fp_args < Argument::n_float_register_parameters_j) {
 379         regs[i].set2(FP_ArgReg[fp_args++]->as_VMReg());
 380       } else {
 381         regs[i].set2(VMRegImpl::stack2reg(stk_args));
 382         stk_args += 2;
 383       }
 384       break;
 385     default:
 386       ShouldNotReachHere();
 387       break;
 388     }
 389   }
 390 
 391   return align_up(stk_args, 2);
 392 }
 393 
 394 // Patch the callers callsite with entry to compiled code if it exists.
 395 static void patch_callers_callsite(MacroAssembler *masm) {
 396   Label L;
 397   __ ldr(rscratch1, Address(rmethod, in_bytes(Method::code_offset())));
 398   __ cbz(rscratch1, L);
 399 
 400   __ enter();
 401   __ push_CPU_state();
 402 
 403   // VM needs caller's callsite
 404   // VM needs target method
 405   // This needs to be a long call since we will relocate this adapter to
 406   // the codeBuffer and it may not reach
 407 
 408 #ifndef PRODUCT
 409   assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
 410 #endif
 411 
 412   __ mov(c_rarg0, rmethod);
 413   __ mov(c_rarg1, lr);
 414   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::fixup_callers_callsite)));
 415   __ blr(rscratch1);
 416 
 417   // Explicit isb required because fixup_callers_callsite may change the code
 418   // stream.
 419   __ safepoint_isb();
 420 
 421   __ pop_CPU_state();
 422   // restore sp
 423   __ leave();
 424   __ bind(L);
 425 }
 426 
 427 static void gen_c2i_adapter(MacroAssembler *masm,
 428                             int total_args_passed,
 429                             int comp_args_on_stack,
 430                             const BasicType *sig_bt,
 431                             const VMRegPair *regs,
 432                             Label& skip_fixup) {
 433   // Before we get into the guts of the C2I adapter, see if we should be here
 434   // at all.  We've come from compiled code and are attempting to jump to the
 435   // interpreter, which means the caller made a static call to get here
 436   // (vcalls always get a compiled target if there is one).  Check for a
 437   // compiled target.  If there is one, we need to patch the caller's call.
 438   patch_callers_callsite(masm);
 439 
 440   __ bind(skip_fixup);
 441 
 442   int words_pushed = 0;
 443 
 444   // Since all args are passed on the stack, total_args_passed *
 445   // Interpreter::stackElementSize is the space we need.
 446 
 447   int extraspace = total_args_passed * Interpreter::stackElementSize;
 448 
 449   __ mov(r13, sp);
 450 
 451   // stack is aligned, keep it that way
 452   extraspace = align_up(extraspace, 2*wordSize);
 453 
 454   if (extraspace)
 455     __ sub(sp, sp, extraspace);
 456 
 457   // Now write the args into the outgoing interpreter space
 458   for (int i = 0; i < total_args_passed; i++) {
 459     if (sig_bt[i] == T_VOID) {
 460       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
 461       continue;
 462     }
 463 
 464     // offset to start parameters
 465     int st_off   = (total_args_passed - i - 1) * Interpreter::stackElementSize;
 466     int next_off = st_off - Interpreter::stackElementSize;
 467 
 468     // Say 4 args:
 469     // i   st_off
 470     // 0   32 T_LONG
 471     // 1   24 T_VOID
 472     // 2   16 T_OBJECT
 473     // 3    8 T_BOOL
 474     // -    0 return address
 475     //
 476     // However to make thing extra confusing. Because we can fit a Java long/double in
 477     // a single slot on a 64 bt vm and it would be silly to break them up, the interpreter
 478     // leaves one slot empty and only stores to a single slot. In this case the
 479     // slot that is occupied is the T_VOID slot. See I said it was confusing.
 480 
 481     VMReg r_1 = regs[i].first();
 482     VMReg r_2 = regs[i].second();
 483     if (!r_1->is_valid()) {
 484       assert(!r_2->is_valid(), "");
 485       continue;
 486     }
 487     if (r_1->is_stack()) {
 488       // memory to memory use rscratch1
 489       int ld_off = (r_1->reg2stack() * VMRegImpl::stack_slot_size
 490                     + extraspace
 491                     + words_pushed * wordSize);
 492       if (!r_2->is_valid()) {
 493         // sign extend??
 494         __ ldrw(rscratch1, Address(sp, ld_off));
 495         __ str(rscratch1, Address(sp, st_off));
 496 
 497       } else {
 498 
 499         __ ldr(rscratch1, Address(sp, ld_off));
 500 
 501         // Two VMREgs|OptoRegs can be T_OBJECT, T_ADDRESS, T_DOUBLE, T_LONG
 502         // T_DOUBLE and T_LONG use two slots in the interpreter
 503         if ( sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
 504           // ld_off == LSW, ld_off+wordSize == MSW
 505           // st_off == MSW, next_off == LSW
 506           __ str(rscratch1, Address(sp, next_off));
 507 #ifdef ASSERT
 508           // Overwrite the unused slot with known junk
 509           __ mov(rscratch1, (uint64_t)0xdeadffffdeadaaaaull);
 510           __ str(rscratch1, Address(sp, st_off));
 511 #endif /* ASSERT */
 512         } else {
 513           __ str(rscratch1, Address(sp, st_off));
 514         }
 515       }
 516     } else if (r_1->is_Register()) {
 517       Register r = r_1->as_Register();
 518       if (!r_2->is_valid()) {
 519         // must be only an int (or less ) so move only 32bits to slot
 520         // why not sign extend??
 521         __ str(r, Address(sp, st_off));
 522       } else {
 523         // Two VMREgs|OptoRegs can be T_OBJECT, T_ADDRESS, T_DOUBLE, T_LONG
 524         // T_DOUBLE and T_LONG use two slots in the interpreter
 525         if ( sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
 526           // jlong/double in gpr
 527 #ifdef ASSERT
 528           // Overwrite the unused slot with known junk
 529           __ mov(rscratch1, (uint64_t)0xdeadffffdeadaaabull);
 530           __ str(rscratch1, Address(sp, st_off));
 531 #endif /* ASSERT */
 532           __ str(r, Address(sp, next_off));
 533         } else {
 534           __ str(r, Address(sp, st_off));
 535         }
 536       }
 537     } else {
 538       assert(r_1->is_FloatRegister(), "");
 539       if (!r_2->is_valid()) {
 540         // only a float use just part of the slot
 541         __ strs(r_1->as_FloatRegister(), Address(sp, st_off));
 542       } else {
 543 #ifdef ASSERT
 544         // Overwrite the unused slot with known junk
 545         __ mov(rscratch1, (uint64_t)0xdeadffffdeadaaacull);
 546         __ str(rscratch1, Address(sp, st_off));
 547 #endif /* ASSERT */
 548         __ strd(r_1->as_FloatRegister(), Address(sp, next_off));
 549       }
 550     }
 551   }
 552 
 553   __ mov(esp, sp); // Interp expects args on caller's expression stack
 554 
 555   __ ldr(rscratch1, Address(rmethod, in_bytes(Method::interpreter_entry_offset())));
 556   __ br(rscratch1);
 557 }
 558 
 559 
 560 void SharedRuntime::gen_i2c_adapter(MacroAssembler *masm,
 561                                     int total_args_passed,
 562                                     int comp_args_on_stack,
 563                                     const BasicType *sig_bt,
 564                                     const VMRegPair *regs) {
 565 
 566   // Note: r13 contains the senderSP on entry. We must preserve it since
 567   // we may do a i2c -> c2i transition if we lose a race where compiled
 568   // code goes non-entrant while we get args ready.
 569 
 570   // In addition we use r13 to locate all the interpreter args because
 571   // we must align the stack to 16 bytes.
 572 
 573   // Adapters are frameless.
 574 
 575   // An i2c adapter is frameless because the *caller* frame, which is
 576   // interpreted, routinely repairs its own esp (from
 577   // interpreter_frame_last_sp), even if a callee has modified the
 578   // stack pointer.  It also recalculates and aligns sp.
 579 
 580   // A c2i adapter is frameless because the *callee* frame, which is
 581   // interpreted, routinely repairs its caller's sp (from sender_sp,
 582   // which is set up via the senderSP register).
 583 
 584   // In other words, if *either* the caller or callee is interpreted, we can
 585   // get the stack pointer repaired after a call.
 586 
 587   // This is why c2i and i2c adapters cannot be indefinitely composed.
 588   // In particular, if a c2i adapter were to somehow call an i2c adapter,
 589   // both caller and callee would be compiled methods, and neither would
 590   // clean up the stack pointer changes performed by the two adapters.
 591   // If this happens, control eventually transfers back to the compiled
 592   // caller, but with an uncorrected stack, causing delayed havoc.
 593 
 594   if (VerifyAdapterCalls &&
 595       (Interpreter::code() != NULL || StubRoutines::code1() != NULL)) {
 596 #if 0
 597     // So, let's test for cascading c2i/i2c adapters right now.
 598     //  assert(Interpreter::contains($return_addr) ||
 599     //         StubRoutines::contains($return_addr),
 600     //         "i2c adapter must return to an interpreter frame");
 601     __ block_comment("verify_i2c { ");
 602     Label L_ok;
 603     if (Interpreter::code() != NULL)
 604       range_check(masm, rax, r11,
 605                   Interpreter::code()->code_start(), Interpreter::code()->code_end(),
 606                   L_ok);
 607     if (StubRoutines::code1() != NULL)
 608       range_check(masm, rax, r11,
 609                   StubRoutines::code1()->code_begin(), StubRoutines::code1()->code_end(),
 610                   L_ok);
 611     if (StubRoutines::code2() != NULL)
 612       range_check(masm, rax, r11,
 613                   StubRoutines::code2()->code_begin(), StubRoutines::code2()->code_end(),
 614                   L_ok);
 615     const char* msg = "i2c adapter must return to an interpreter frame";
 616     __ block_comment(msg);
 617     __ stop(msg);
 618     __ bind(L_ok);
 619     __ block_comment("} verify_i2ce ");
 620 #endif
 621   }
 622 
 623   // Cut-out for having no stack args.
 624   int comp_words_on_stack = align_up(comp_args_on_stack*VMRegImpl::stack_slot_size, wordSize)>>LogBytesPerWord;
 625   if (comp_args_on_stack) {
 626     __ sub(rscratch1, sp, comp_words_on_stack * wordSize);
 627     __ andr(sp, rscratch1, -16);
 628   }
 629 
 630   // Will jump to the compiled code just as if compiled code was doing it.
 631   // Pre-load the register-jump target early, to schedule it better.
 632   __ ldr(rscratch1, Address(rmethod, in_bytes(Method::from_compiled_offset())));
 633 
 634 #if INCLUDE_JVMCI
 635   if (EnableJVMCI) {
 636     // check if this call should be routed towards a specific entry point
 637     __ ldr(rscratch2, Address(rthread, in_bytes(JavaThread::jvmci_alternate_call_target_offset())));
 638     Label no_alternative_target;
 639     __ cbz(rscratch2, no_alternative_target);
 640     __ mov(rscratch1, rscratch2);
 641     __ str(zr, Address(rthread, in_bytes(JavaThread::jvmci_alternate_call_target_offset())));
 642     __ bind(no_alternative_target);
 643   }
 644 #endif // INCLUDE_JVMCI
 645 
 646   // Now generate the shuffle code.
 647   for (int i = 0; i < total_args_passed; i++) {
 648     if (sig_bt[i] == T_VOID) {
 649       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
 650       continue;
 651     }
 652 
 653     // Pick up 0, 1 or 2 words from SP+offset.
 654 
 655     assert(!regs[i].second()->is_valid() || regs[i].first()->next() == regs[i].second(),
 656             "scrambled load targets?");
 657     // Load in argument order going down.
 658     int ld_off = (total_args_passed - i - 1)*Interpreter::stackElementSize;
 659     // Point to interpreter value (vs. tag)
 660     int next_off = ld_off - Interpreter::stackElementSize;
 661     //
 662     //
 663     //
 664     VMReg r_1 = regs[i].first();
 665     VMReg r_2 = regs[i].second();
 666     if (!r_1->is_valid()) {
 667       assert(!r_2->is_valid(), "");
 668       continue;
 669     }
 670     if (r_1->is_stack()) {
 671       // Convert stack slot to an SP offset (+ wordSize to account for return address )
 672       int st_off = regs[i].first()->reg2stack()*VMRegImpl::stack_slot_size;
 673       if (!r_2->is_valid()) {
 674         // sign extend???
 675         __ ldrsw(rscratch2, Address(esp, ld_off));
 676         __ str(rscratch2, Address(sp, st_off));
 677       } else {
 678         //
 679         // We are using two optoregs. This can be either T_OBJECT,
 680         // T_ADDRESS, T_LONG, or T_DOUBLE the interpreter allocates
 681         // two slots but only uses one for thr T_LONG or T_DOUBLE case
 682         // So we must adjust where to pick up the data to match the
 683         // interpreter.
 684         //
 685         // Interpreter local[n] == MSW, local[n+1] == LSW however locals
 686         // are accessed as negative so LSW is at LOW address
 687 
 688         // ld_off is MSW so get LSW
 689         const int offset = (sig_bt[i]==T_LONG||sig_bt[i]==T_DOUBLE)?
 690                            next_off : ld_off;
 691         __ ldr(rscratch2, Address(esp, offset));
 692         // st_off is LSW (i.e. reg.first())
 693         __ str(rscratch2, Address(sp, st_off));
 694       }
 695     } else if (r_1->is_Register()) {  // Register argument
 696       Register r = r_1->as_Register();
 697       if (r_2->is_valid()) {
 698         //
 699         // We are using two VMRegs. This can be either T_OBJECT,
 700         // T_ADDRESS, T_LONG, or T_DOUBLE the interpreter allocates
 701         // two slots but only uses one for thr T_LONG or T_DOUBLE case
 702         // So we must adjust where to pick up the data to match the
 703         // interpreter.
 704 
 705         const int offset = (sig_bt[i]==T_LONG||sig_bt[i]==T_DOUBLE)?
 706                            next_off : ld_off;
 707 
 708         // this can be a misaligned move
 709         __ ldr(r, Address(esp, offset));
 710       } else {
 711         // sign extend and use a full word?
 712         __ ldrw(r, Address(esp, ld_off));
 713       }
 714     } else {
 715       if (!r_2->is_valid()) {
 716         __ ldrs(r_1->as_FloatRegister(), Address(esp, ld_off));
 717       } else {
 718         __ ldrd(r_1->as_FloatRegister(), Address(esp, next_off));
 719       }
 720     }
 721   }
 722 
 723   __ mov(rscratch2, rscratch1);
 724   __ push_cont_fastpath(rthread); // Set JavaThread::_cont_fastpath to the sp of the oldest interpreted frame we know about; kills rscratch1
 725   __ mov(rscratch1, rscratch2);
 726 
 727   // 6243940 We might end up in handle_wrong_method if
 728   // the callee is deoptimized as we race thru here. If that
 729   // happens we don't want to take a safepoint because the
 730   // caller frame will look interpreted and arguments are now
 731   // "compiled" so it is much better to make this transition
 732   // invisible to the stack walking code. Unfortunately if
 733   // we try and find the callee by normal means a safepoint
 734   // is possible. So we stash the desired callee in the thread
 735   // and the vm will find there should this case occur.
 736 
 737   __ str(rmethod, Address(rthread, JavaThread::callee_target_offset()));
 738 
 739   __ br(rscratch1);
 740 }
 741 
 742 // ---------------------------------------------------------------
 743 AdapterHandlerEntry* SharedRuntime::generate_i2c2i_adapters(MacroAssembler *masm,
 744                                                             int total_args_passed,
 745                                                             int comp_args_on_stack,
 746                                                             const BasicType *sig_bt,
 747                                                             const VMRegPair *regs,
 748                                                             AdapterFingerPrint* fingerprint) {
 749   address i2c_entry = __ pc();
 750 
 751   gen_i2c_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs);
 752 
 753   address c2i_unverified_entry = __ pc();
 754   Label skip_fixup;
 755 
 756   Label ok;
 757 
 758   Register holder = rscratch2;
 759   Register receiver = j_rarg0;
 760   Register tmp = r10;  // A call-clobbered register not used for arg passing
 761 
 762   // -------------------------------------------------------------------------
 763   // Generate a C2I adapter.  On entry we know rmethod holds the Method* during calls
 764   // to the interpreter.  The args start out packed in the compiled layout.  They
 765   // need to be unpacked into the interpreter layout.  This will almost always
 766   // require some stack space.  We grow the current (compiled) stack, then repack
 767   // the args.  We  finally end in a jump to the generic interpreter entry point.
 768   // On exit from the interpreter, the interpreter will restore our SP (lest the
 769   // compiled code, which relys solely on SP and not FP, get sick).
 770 
 771   {
 772     __ block_comment("c2i_unverified_entry {");
 773     __ load_klass(rscratch1, receiver);
 774     __ ldr(tmp, Address(holder, CompiledICHolder::holder_klass_offset()));
 775     __ cmp(rscratch1, tmp);
 776     __ ldr(rmethod, Address(holder, CompiledICHolder::holder_metadata_offset()));
 777     __ br(Assembler::EQ, ok);
 778     __ far_jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 779 
 780     __ bind(ok);
 781     // Method might have been compiled since the call site was patched to
 782     // interpreted; if that is the case treat it as a miss so we can get
 783     // the call site corrected.
 784     __ ldr(rscratch1, Address(rmethod, in_bytes(Method::code_offset())));
 785     __ cbz(rscratch1, skip_fixup);
 786     __ far_jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 787     __ block_comment("} c2i_unverified_entry");
 788   }
 789 
 790   address c2i_entry = __ pc();
 791 
 792   // Class initialization barrier for static methods
 793   address c2i_no_clinit_check_entry = NULL;
 794   if (VM_Version::supports_fast_class_init_checks()) {
 795     Label L_skip_barrier;
 796 
 797     { // Bypass the barrier for non-static methods
 798       __ ldrw(rscratch1, Address(rmethod, Method::access_flags_offset()));
 799       __ andsw(zr, rscratch1, JVM_ACC_STATIC);
 800       __ br(Assembler::EQ, L_skip_barrier); // non-static
 801     }
 802 
 803     __ load_method_holder(rscratch2, rmethod);
 804     __ clinit_barrier(rscratch2, rscratch1, &L_skip_barrier);
 805     __ far_jump(RuntimeAddress(SharedRuntime::get_handle_wrong_method_stub()));
 806 
 807     __ bind(L_skip_barrier);
 808     c2i_no_clinit_check_entry = __ pc();
 809   }
 810 
 811   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
 812   bs->c2i_entry_barrier(masm);
 813 
 814   gen_c2i_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs, skip_fixup);
 815 
 816   __ flush();
 817   return AdapterHandlerLibrary::new_entry(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry, c2i_no_clinit_check_entry);
 818 }
 819 
 820 static int c_calling_convention_priv(const BasicType *sig_bt,
 821                                          VMRegPair *regs,
 822                                          VMRegPair *regs2,
 823                                          int total_args_passed) {
 824   assert(regs2 == NULL, "not needed on AArch64");
 825 
 826 // We return the amount of VMRegImpl stack slots we need to reserve for all
 827 // the arguments NOT counting out_preserve_stack_slots.
 828 
 829     static const Register INT_ArgReg[Argument::n_int_register_parameters_c] = {
 830       c_rarg0, c_rarg1, c_rarg2, c_rarg3, c_rarg4, c_rarg5,  c_rarg6,  c_rarg7
 831     };
 832     static const FloatRegister FP_ArgReg[Argument::n_float_register_parameters_c] = {
 833       c_farg0, c_farg1, c_farg2, c_farg3,
 834       c_farg4, c_farg5, c_farg6, c_farg7
 835     };
 836 
 837     uint int_args = 0;
 838     uint fp_args = 0;
 839     uint stk_args = 0; // inc by 2 each time
 840 
 841     for (int i = 0; i < total_args_passed; i++) {
 842       switch (sig_bt[i]) {
 843       case T_BOOLEAN:
 844       case T_CHAR:
 845       case T_BYTE:
 846       case T_SHORT:
 847       case T_INT:
 848         if (int_args < Argument::n_int_register_parameters_c) {
 849           regs[i].set1(INT_ArgReg[int_args++]->as_VMReg());
 850         } else {
 851 #ifdef __APPLE__
 852           // Less-than word types are stored one after another.
 853           // The code is unable to handle this so bailout.
 854           return -1;
 855 #endif
 856           regs[i].set1(VMRegImpl::stack2reg(stk_args));
 857           stk_args += 2;
 858         }
 859         break;
 860       case T_LONG:
 861         assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
 862         // fall through
 863       case T_OBJECT:
 864       case T_ARRAY:
 865       case T_ADDRESS:
 866       case T_METADATA:
 867         if (int_args < Argument::n_int_register_parameters_c) {
 868           regs[i].set2(INT_ArgReg[int_args++]->as_VMReg());
 869         } else {
 870           regs[i].set2(VMRegImpl::stack2reg(stk_args));
 871           stk_args += 2;
 872         }
 873         break;
 874       case T_FLOAT:
 875         if (fp_args < Argument::n_float_register_parameters_c) {
 876           regs[i].set1(FP_ArgReg[fp_args++]->as_VMReg());
 877         } else {
 878 #ifdef __APPLE__
 879           // Less-than word types are stored one after another.
 880           // The code is unable to handle this so bailout.
 881           return -1;
 882 #endif
 883           regs[i].set1(VMRegImpl::stack2reg(stk_args));
 884           stk_args += 2;
 885         }
 886         break;
 887       case T_DOUBLE:
 888         assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
 889         if (fp_args < Argument::n_float_register_parameters_c) {
 890           regs[i].set2(FP_ArgReg[fp_args++]->as_VMReg());
 891         } else {
 892           regs[i].set2(VMRegImpl::stack2reg(stk_args));
 893           stk_args += 2;
 894         }
 895         break;
 896       case T_VOID: // Halves of longs and doubles
 897         assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
 898         regs[i].set_bad();
 899         break;
 900       default:
 901         ShouldNotReachHere();
 902         break;
 903       }
 904     }
 905 
 906   return stk_args;
 907 }
 908 
 909 int SharedRuntime::vector_calling_convention(VMRegPair *regs,
 910                                              uint num_bits,
 911                                              uint total_args_passed) {
 912   Unimplemented();
 913   return 0;
 914 }
 915 
 916 int SharedRuntime::c_calling_convention(const BasicType *sig_bt,
 917                                          VMRegPair *regs,
 918                                          VMRegPair *regs2,
 919                                          int total_args_passed)
 920 {
 921   int result = c_calling_convention_priv(sig_bt, regs, regs2, total_args_passed);
 922   guarantee(result >= 0, "Unsupported arguments configuration");
 923   return result;
 924 }
 925 
 926 // On 64 bit we will store integer like items to the stack as
 927 // 64 bits items (Aarch64 abi) even though java would only store
 928 // 32bits for a parameter. On 32bit it will simply be 32 bits
 929 // So this routine will do 32->32 on 32bit and 32->64 on 64bit
 930 static void move32_64(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
 931   if (src.first()->is_stack()) {
 932     if (dst.first()->is_stack()) {
 933       // stack to stack
 934       __ ldr(rscratch1, Address(rfp, reg2offset_in(src.first())));
 935       __ str(rscratch1, Address(sp, reg2offset_out(dst.first())));
 936     } else {
 937       // stack to reg
 938       __ ldrsw(dst.first()->as_Register(), Address(rfp, reg2offset_in(src.first())));
 939     }
 940   } else if (dst.first()->is_stack()) {
 941     // reg to stack
 942     // Do we really have to sign extend???
 943     // __ movslq(src.first()->as_Register(), src.first()->as_Register());
 944     __ str(src.first()->as_Register(), Address(sp, reg2offset_out(dst.first())));
 945   } else {
 946     if (dst.first() != src.first()) {
 947       __ sxtw(dst.first()->as_Register(), src.first()->as_Register());
 948     }
 949   }
 950 }
 951 
 952 // An oop arg. Must pass a handle not the oop itself
 953 static void object_move(MacroAssembler* masm,
 954                         OopMap* map,
 955                         int oop_handle_offset,
 956                         int framesize_in_slots,
 957                         VMRegPair src,
 958                         VMRegPair dst,
 959                         bool is_receiver,
 960                         int* receiver_offset) {
 961 
 962   // must pass a handle. First figure out the location we use as a handle
 963 
 964   Register rHandle = dst.first()->is_stack() ? rscratch2 : dst.first()->as_Register();
 965 
 966   // See if oop is NULL if it is we need no handle
 967 
 968   if (src.first()->is_stack()) {
 969 
 970     // Oop is already on the stack as an argument
 971     int offset_in_older_frame = src.first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
 972     map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + framesize_in_slots));
 973     if (is_receiver) {
 974       *receiver_offset = (offset_in_older_frame + framesize_in_slots) * VMRegImpl::stack_slot_size;
 975     }
 976 
 977     __ ldr(rscratch1, Address(rfp, reg2offset_in(src.first())));
 978     __ lea(rHandle, Address(rfp, reg2offset_in(src.first())));
 979     // conditionally move a NULL
 980     __ cmp(rscratch1, zr);
 981     __ csel(rHandle, zr, rHandle, Assembler::EQ);
 982   } else {
 983 
 984     // Oop is in an a register we must store it to the space we reserve
 985     // on the stack for oop_handles and pass a handle if oop is non-NULL
 986 
 987     const Register rOop = src.first()->as_Register();
 988     int oop_slot;
 989     if (rOop == j_rarg0)
 990       oop_slot = 0;
 991     else if (rOop == j_rarg1)
 992       oop_slot = 1;
 993     else if (rOop == j_rarg2)
 994       oop_slot = 2;
 995     else if (rOop == j_rarg3)
 996       oop_slot = 3;
 997     else if (rOop == j_rarg4)
 998       oop_slot = 4;
 999     else if (rOop == j_rarg5)
1000       oop_slot = 5;
1001     else if (rOop == j_rarg6)
1002       oop_slot = 6;
1003     else {
1004       assert(rOop == j_rarg7, "wrong register");
1005       oop_slot = 7;
1006     }
1007 
1008     oop_slot = oop_slot * VMRegImpl::slots_per_word + oop_handle_offset;
1009     int offset = oop_slot*VMRegImpl::stack_slot_size;
1010 
1011     map->set_oop(VMRegImpl::stack2reg(oop_slot));
1012     // Store oop in handle area, may be NULL
1013     __ str(rOop, Address(sp, offset));
1014     if (is_receiver) {
1015       *receiver_offset = offset;
1016     }
1017 
1018     __ cmp(rOop, zr);
1019     __ lea(rHandle, Address(sp, offset));
1020     // conditionally move a NULL
1021     __ csel(rHandle, zr, rHandle, Assembler::EQ);
1022   }
1023 
1024   // If arg is on the stack then place it otherwise it is already in correct reg.
1025   if (dst.first()->is_stack()) {
1026     __ str(rHandle, Address(sp, reg2offset_out(dst.first())));
1027   }
1028 }
1029 
1030 // A float arg may have to do float reg int reg conversion
1031 static void float_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1032   assert(src.first()->is_stack() && dst.first()->is_stack() ||
1033          src.first()->is_reg() && dst.first()->is_reg(), "Unexpected error");
1034   if (src.first()->is_stack()) {
1035     if (dst.first()->is_stack()) {
1036       __ ldrw(rscratch1, Address(rfp, reg2offset_in(src.first())));
1037       __ strw(rscratch1, Address(sp, reg2offset_out(dst.first())));
1038     } else {
1039       ShouldNotReachHere();
1040     }
1041   } else if (src.first() != dst.first()) {
1042     if (src.is_single_phys_reg() && dst.is_single_phys_reg())
1043       __ fmovs(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
1044     else
1045       ShouldNotReachHere();
1046   }
1047 }
1048 
1049 // A long move
1050 static void long_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1051   if (src.first()->is_stack()) {
1052     if (dst.first()->is_stack()) {
1053       // stack to stack
1054       __ ldr(rscratch1, Address(rfp, reg2offset_in(src.first())));
1055       __ str(rscratch1, Address(sp, reg2offset_out(dst.first())));
1056     } else {
1057       // stack to reg
1058       __ ldr(dst.first()->as_Register(), Address(rfp, reg2offset_in(src.first())));
1059     }
1060   } else if (dst.first()->is_stack()) {
1061     // reg to stack
1062     // Do we really have to sign extend???
1063     // __ movslq(src.first()->as_Register(), src.first()->as_Register());
1064     __ str(src.first()->as_Register(), Address(sp, reg2offset_out(dst.first())));
1065   } else {
1066     if (dst.first() != src.first()) {
1067       __ mov(dst.first()->as_Register(), src.first()->as_Register());
1068     }
1069   }
1070 }
1071 
1072 
1073 // A double move
1074 static void double_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1075   assert(src.first()->is_stack() && dst.first()->is_stack() ||
1076          src.first()->is_reg() && dst.first()->is_reg(), "Unexpected error");
1077   if (src.first()->is_stack()) {
1078     if (dst.first()->is_stack()) {
1079       __ ldr(rscratch1, Address(rfp, reg2offset_in(src.first())));
1080       __ str(rscratch1, Address(sp, reg2offset_out(dst.first())));
1081     } else {
1082       ShouldNotReachHere();
1083     }
1084   } else if (src.first() != dst.first()) {
1085     if (src.is_single_phys_reg() && dst.is_single_phys_reg())
1086       __ fmovd(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
1087     else
1088       ShouldNotReachHere();
1089   }
1090 }
1091 
1092 
1093 void SharedRuntime::save_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1094   // We always ignore the frame_slots arg and just use the space just below frame pointer
1095   // which by this time is free to use
1096   switch (ret_type) {
1097   case T_FLOAT:
1098     __ strs(v0, Address(rfp, -wordSize));
1099     break;
1100   case T_DOUBLE:
1101     __ strd(v0, Address(rfp, -wordSize));
1102     break;
1103   case T_VOID:  break;
1104   default: {
1105     __ str(r0, Address(rfp, -wordSize));
1106     }
1107   }
1108 }
1109 
1110 void SharedRuntime::restore_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1111   // We always ignore the frame_slots arg and just use the space just below frame pointer
1112   // which by this time is free to use
1113   switch (ret_type) {
1114   case T_FLOAT:
1115     __ ldrs(v0, Address(rfp, -wordSize));
1116     break;
1117   case T_DOUBLE:
1118     __ ldrd(v0, Address(rfp, -wordSize));
1119     break;
1120   case T_VOID:  break;
1121   default: {
1122     __ ldr(r0, Address(rfp, -wordSize));
1123     }
1124   }
1125 }
1126 static void save_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
1127   RegSet x;
1128   for ( int i = first_arg ; i < arg_count ; i++ ) {
1129     if (args[i].first()->is_Register()) {
1130       x = x + args[i].first()->as_Register();
1131     } else if (args[i].first()->is_FloatRegister()) {
1132       __ strd(args[i].first()->as_FloatRegister(), Address(__ pre(sp, -2 * wordSize)));
1133     }
1134   }
1135   __ push(x, sp);
1136 }
1137 
1138 static void restore_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
1139   RegSet x;
1140   for ( int i = first_arg ; i < arg_count ; i++ ) {
1141     if (args[i].first()->is_Register()) {
1142       x = x + args[i].first()->as_Register();
1143     } else {
1144       ;
1145     }
1146   }
1147   __ pop(x, sp);
1148   for ( int i = arg_count - 1 ; i >= first_arg ; i-- ) {
1149     if (args[i].first()->is_Register()) {
1150       ;
1151     } else if (args[i].first()->is_FloatRegister()) {
1152       __ ldrd(args[i].first()->as_FloatRegister(), Address(__ post(sp, 2 * wordSize)));
1153     }
1154   }
1155 }
1156 
1157 static void rt_call(MacroAssembler* masm, address dest) {
1158   CodeBlob *cb = CodeCache::find_blob(dest);
1159   if (cb) {
1160     __ far_call(RuntimeAddress(dest));
1161   } else {
1162     __ lea(rscratch1, RuntimeAddress(dest));
1163     __ blr(rscratch1);
1164   }
1165 }
1166 
1167 static void verify_oop_args(MacroAssembler* masm,
1168                             const methodHandle& method,
1169                             const BasicType* sig_bt,
1170                             const VMRegPair* regs) {
1171   Register temp_reg = r19;  // not part of any compiled calling seq
1172   if (VerifyOops) {
1173     for (int i = 0; i < method->size_of_parameters(); i++) {
1174       if (sig_bt[i] == T_OBJECT ||
1175           sig_bt[i] == T_ARRAY) {
1176         VMReg r = regs[i].first();
1177         assert(r->is_valid(), "bad oop arg");
1178         if (r->is_stack()) {
1179           __ ldr(temp_reg, Address(sp, r->reg2stack() * VMRegImpl::stack_slot_size));
1180           __ verify_oop(temp_reg);
1181         } else {
1182           __ verify_oop(r->as_Register());
1183         }
1184       }
1185     }
1186   }
1187 }
1188 
1189 // defined in stubGenerator_aarch64.cpp
1190 OopMap* continuation_enter_setup(MacroAssembler* masm, int& stack_slots);
1191 void fill_continuation_entry(MacroAssembler* masm);
1192 void continuation_enter_cleanup(MacroAssembler* masm);
1193 
1194 // enterSpecial(Continuation c, boolean isContinue)
1195 // On entry: c_rarg1 -- the continuation object
1196 //           c_rarg2 -- isContinue
1197 static void gen_continuation_enter(MacroAssembler* masm,
1198                                  const methodHandle& method,
1199                                  const BasicType* sig_bt,
1200                                  const VMRegPair* regs,
1201                                  int& exception_offset,
1202                                  OopMapSet*oop_maps,
1203                                  int& frame_complete,
1204                                  int& stack_slots) {
1205   //verify_oop_args(masm, method, sig_bt, regs);
1206   Address resolve(SharedRuntime::get_resolve_static_call_stub(), 
1207                   relocInfo::static_call_type);
1208 
1209   stack_slots = 2; // will be overwritten
1210   address start = __ pc();
1211 
1212   Label call_thaw, exit;
1213 
1214   __ enter(); // push(rbp);
1215 
1216   //BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
1217   //bs->nmethod_entry_barrier(masm);
1218   OopMap* map = continuation_enter_setup(masm, stack_slots);
1219 
1220   // Frame is now completed as far as size and linkage.
1221   frame_complete =__ pc() - start;
1222 
1223   fill_continuation_entry(masm);
1224 
1225   __ cmp(c_rarg2, (u1)0);
1226   __ br(Assembler::NE, call_thaw);
1227   
1228   address mark = __ pc();
1229 //  __ relocate(resolve.rspec());
1230   //if (!far_branches()) {
1231 //  __ bl(resolve.target()); 
1232   __ trampoline_call1(resolve, NULL, false);
1233 
1234   oop_maps->add_gc_map(__ pc() - start, map);
1235   __ post_call_nop();
1236 
1237   __ b(exit);
1238 
1239   __ bind(call_thaw);
1240 
1241   rt_call(masm, CAST_FROM_FN_PTR(address, StubRoutines::cont_thaw()));
1242   oop_maps->add_gc_map(__ pc() - start, map->deep_copy());
1243   ContinuationEntry::return_pc_offset = __ pc() - start;
1244   __ post_call_nop();
1245 
1246   __ bind(exit);
1247   continuation_enter_cleanup(masm);
1248   __ leave();
1249   __ ret(lr);
1250 
1251   /// exception handling
1252 
1253   exception_offset = __ pc() - start;
1254   {
1255       __ mov(r19, r0); // save return value contaning the exception oop in callee-saved R19
1256   
1257       continuation_enter_cleanup(masm);
1258       // __ mov(sp, rfp);
1259   
1260       __ ldr(c_rarg1, Address(rfp, wordSize)); // return address
1261       __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::exception_handler_for_return_address), rthread, c_rarg1);
1262 
1263       // see OptoRuntime::generate_exception_blob: r0 -- exception oop, r3 -- exception pc
1264 
1265       __ mov(r1, r0); // the exception handler
1266       __ mov(r0, r19); // restore return value contaning the exception oop
1267       __ verify_oop(r0);
1268 
1269       __ leave();
1270       __ mov(r3, lr);
1271       __ br(r1); // the exception handler
1272   }
1273 
1274   CodeBuffer* cbuf = masm->code_section()->outer();
1275   address stub = CompiledStaticCall::emit_to_interp_stub(*cbuf, mark);
1276 }
1277 
1278 static void gen_special_dispatch(MacroAssembler* masm,
1279                                  const methodHandle& method,
1280                                  const BasicType* sig_bt,
1281                                  const VMRegPair* regs) {
1282   verify_oop_args(masm, method, sig_bt, regs);
1283   vmIntrinsics::ID iid = method->intrinsic_id();
1284 
1285   // Now write the args into the outgoing interpreter space
1286   bool     has_receiver   = false;
1287   Register receiver_reg   = noreg;
1288   int      member_arg_pos = -1;
1289   Register member_reg     = noreg;
1290   int      ref_kind       = MethodHandles::signature_polymorphic_intrinsic_ref_kind(iid);
1291   if (ref_kind != 0) {
1292     member_arg_pos = method->size_of_parameters() - 1;  // trailing MemberName argument
1293     member_reg = r19;  // known to be free at this point
1294     has_receiver = MethodHandles::ref_kind_has_receiver(ref_kind);
1295   } else if (iid == vmIntrinsics::_invokeBasic || iid == vmIntrinsics::_linkToNative) {
1296     has_receiver = true;
1297   } else {
1298     fatal("unexpected intrinsic id %d", vmIntrinsics::as_int(iid));
1299   }
1300 
1301   if (member_reg != noreg) {
1302     // Load the member_arg into register, if necessary.
1303     SharedRuntime::check_member_name_argument_is_last_argument(method, sig_bt, regs);
1304     VMReg r = regs[member_arg_pos].first();
1305     if (r->is_stack()) {
1306       __ ldr(member_reg, Address(sp, r->reg2stack() * VMRegImpl::stack_slot_size));
1307     } else {
1308       // no data motion is needed
1309       member_reg = r->as_Register();
1310     }
1311   }
1312 
1313   if (has_receiver) {
1314     // Make sure the receiver is loaded into a register.
1315     assert(method->size_of_parameters() > 0, "oob");
1316     assert(sig_bt[0] == T_OBJECT, "receiver argument must be an object");
1317     VMReg r = regs[0].first();
1318     assert(r->is_valid(), "bad receiver arg");
1319     if (r->is_stack()) {
1320       // Porting note:  This assumes that compiled calling conventions always
1321       // pass the receiver oop in a register.  If this is not true on some
1322       // platform, pick a temp and load the receiver from stack.
1323       fatal("receiver always in a register");
1324       receiver_reg = r2;  // known to be free at this point
1325       __ ldr(receiver_reg, Address(sp, r->reg2stack() * VMRegImpl::stack_slot_size));
1326     } else {
1327       // no data motion is needed
1328       receiver_reg = r->as_Register();
1329     }
1330   }
1331 
1332   // Figure out which address we are really jumping to:
1333   MethodHandles::generate_method_handle_dispatch(masm, iid,
1334                                                  receiver_reg, member_reg, /*for_compiler_entry:*/ true);
1335 }
1336 
1337 // ---------------------------------------------------------------------------
1338 // Generate a native wrapper for a given method.  The method takes arguments
1339 // in the Java compiled code convention, marshals them to the native
1340 // convention (handlizes oops, etc), transitions to native, makes the call,
1341 // returns to java state (possibly blocking), unhandlizes any result and
1342 // returns.
1343 //
1344 // Critical native functions are a shorthand for the use of
1345 // GetPrimtiveArrayCritical and disallow the use of any other JNI
1346 // functions.  The wrapper is expected to unpack the arguments before
1347 // passing them to the callee. Critical native functions leave the state _in_Java,
1348 // since they block out GC.
1349 // Some other parts of JNI setup are skipped like the tear down of the JNI handle
1350 // block and the check for pending exceptions it's impossible for them
1351 // to be thrown.
1352 //
1353 nmethod* SharedRuntime::generate_native_wrapper(MacroAssembler* masm,
1354                                                 const methodHandle& method,
1355                                                 int compile_id,
1356                                                 BasicType* in_sig_bt,
1357                                                 VMRegPair* in_regs,
1358                                                 BasicType ret_type) {
1359   if (method->is_continuation_enter_intrinsic()) {
1360     vmIntrinsics::ID iid = method->intrinsic_id();
1361     intptr_t start = (intptr_t)__ pc();
1362     int vep_offset = ((intptr_t)__ pc()) - start;
1363     int exception_offset = 0;
1364     int frame_complete = 0;
1365     int stack_slots = 0;
1366     OopMapSet* oop_maps =  new OopMapSet();
1367     gen_continuation_enter(masm,
1368                          method,
1369                          in_sig_bt,
1370                          in_regs,
1371                          exception_offset,
1372                          oop_maps,
1373                          frame_complete,
1374                          stack_slots);
1375     __ flush();
1376     nmethod* nm = nmethod::new_native_nmethod(method,
1377                                               compile_id,
1378                                               masm->code(),
1379                                               vep_offset,
1380                                               frame_complete,
1381                                               stack_slots,
1382                                               in_ByteSize(-1),
1383                                               in_ByteSize(-1),
1384                                               oop_maps,
1385                                               exception_offset);
1386     ContinuationEntry::set_enter_nmethod(nm);
1387     return nm;
1388   }
1389 
1390   if (method->is_method_handle_intrinsic()) {
1391     vmIntrinsics::ID iid = method->intrinsic_id();
1392     intptr_t start = (intptr_t)__ pc();
1393     int vep_offset = ((intptr_t)__ pc()) - start;
1394 
1395     // First instruction must be a nop as it may need to be patched on deoptimisation
1396     __ nop();
1397     gen_special_dispatch(masm,
1398                          method,
1399                          in_sig_bt,
1400                          in_regs);
1401     int frame_complete = ((intptr_t)__ pc()) - start;  // not complete, period
1402     __ flush();
1403     int stack_slots = SharedRuntime::out_preserve_stack_slots();  // no out slots at all, actually
1404     return nmethod::new_native_nmethod(method,
1405                                        compile_id,
1406                                        masm->code(),
1407                                        vep_offset,
1408                                        frame_complete,
1409                                        stack_slots / VMRegImpl::slots_per_word,
1410                                        in_ByteSize(-1),
1411                                        in_ByteSize(-1),
1412                                        (OopMapSet*)NULL);
1413   }
1414   address native_func = method->native_function();
1415   assert(native_func != NULL, "must have function");
1416 
1417   // An OopMap for lock (and class if static)
1418   OopMapSet *oop_maps = new OopMapSet();
1419   intptr_t start = (intptr_t)__ pc();
1420 
1421   // We have received a description of where all the java arg are located
1422   // on entry to the wrapper. We need to convert these args to where
1423   // the jni function will expect them. To figure out where they go
1424   // we convert the java signature to a C signature by inserting
1425   // the hidden arguments as arg[0] and possibly arg[1] (static method)
1426 
1427   const int total_in_args = method->size_of_parameters();
1428   int total_c_args = total_in_args + (method->is_static() ? 2 : 1);
1429 
1430   BasicType* out_sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_c_args);
1431   VMRegPair* out_regs   = NEW_RESOURCE_ARRAY(VMRegPair, total_c_args);
1432   BasicType* in_elem_bt = NULL;
1433 
1434   int argc = 0;
1435   out_sig_bt[argc++] = T_ADDRESS;
1436   if (method->is_static()) {
1437     out_sig_bt[argc++] = T_OBJECT;
1438   }
1439 
1440   for (int i = 0; i < total_in_args ; i++ ) {
1441     out_sig_bt[argc++] = in_sig_bt[i];
1442   }
1443 
1444   // Now figure out where the args must be stored and how much stack space
1445   // they require.
1446   int out_arg_slots;
1447   out_arg_slots = c_calling_convention_priv(out_sig_bt, out_regs, NULL, total_c_args);
1448 
1449   if (out_arg_slots < 0) {
1450     return NULL;
1451   }
1452 
1453   // Compute framesize for the wrapper.  We need to handlize all oops in
1454   // incoming registers
1455 
1456   // Calculate the total number of stack slots we will need.
1457 
1458   // First count the abi requirement plus all of the outgoing args
1459   int stack_slots = SharedRuntime::out_preserve_stack_slots() + out_arg_slots;
1460 
1461   // Now the space for the inbound oop handle area
1462   int total_save_slots = 8 * VMRegImpl::slots_per_word;  // 8 arguments passed in registers
1463 
1464   int oop_handle_offset = stack_slots;
1465   stack_slots += total_save_slots;
1466 
1467   // Now any space we need for handlizing a klass if static method
1468 
1469   int klass_slot_offset = 0;
1470   int klass_offset = -1;
1471   int lock_slot_offset = 0;
1472   bool is_static = false;
1473 
1474   if (method->is_static()) {
1475     klass_slot_offset = stack_slots;
1476     stack_slots += VMRegImpl::slots_per_word;
1477     klass_offset = klass_slot_offset * VMRegImpl::stack_slot_size;
1478     is_static = true;
1479   }
1480 
1481   // Plus a lock if needed
1482 
1483   if (method->is_synchronized()) {
1484     lock_slot_offset = stack_slots;
1485     stack_slots += VMRegImpl::slots_per_word;
1486   }
1487 
1488   // Now a place (+2) to save return values or temp during shuffling
1489   // + 4 for return address (which we own) and saved rfp
1490   stack_slots += 6;
1491 
1492   // Ok The space we have allocated will look like:
1493   //
1494   //
1495   // FP-> |                     |
1496   //      |---------------------|
1497   //      | 2 slots for moves   |
1498   //      |---------------------|
1499   //      | lock box (if sync)  |
1500   //      |---------------------| <- lock_slot_offset
1501   //      | klass (if static)   |
1502   //      |---------------------| <- klass_slot_offset
1503   //      | oopHandle area      |
1504   //      |---------------------| <- oop_handle_offset (8 java arg registers)
1505   //      | outbound memory     |
1506   //      | based arguments     |
1507   //      |                     |
1508   //      |---------------------|
1509   //      |                     |
1510   // SP-> | out_preserved_slots |
1511   //
1512   //
1513 
1514 
1515   // Now compute actual number of stack words we need rounding to make
1516   // stack properly aligned.
1517   stack_slots = align_up(stack_slots, StackAlignmentInSlots);
1518 
1519   int stack_size = stack_slots * VMRegImpl::stack_slot_size;
1520 
1521   // First thing make an ic check to see if we should even be here
1522 
1523   // We are free to use all registers as temps without saving them and
1524   // restoring them except rfp. rfp is the only callee save register
1525   // as far as the interpreter and the compiler(s) are concerned.
1526 
1527 
1528   const Register ic_reg = rscratch2;
1529   const Register receiver = j_rarg0;
1530 
1531   Label hit;
1532   Label exception_pending;
1533 
1534   assert_different_registers(ic_reg, receiver, rscratch1);
1535   __ verify_oop(receiver);
1536   __ cmp_klass(receiver, ic_reg, rscratch1);
1537   __ br(Assembler::EQ, hit);
1538 
1539   __ far_jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
1540 
1541   // Verified entry point must be aligned
1542   __ align(8);
1543 
1544   __ bind(hit);
1545 
1546   int vep_offset = ((intptr_t)__ pc()) - start;
1547 
1548   // If we have to make this method not-entrant we'll overwrite its
1549   // first instruction with a jump.  For this action to be legal we
1550   // must ensure that this first instruction is a B, BL, NOP, BKPT,
1551   // SVC, HVC, or SMC.  Make it a NOP.
1552   __ nop();
1553 
1554   if (VM_Version::supports_fast_class_init_checks() && method->needs_clinit_barrier()) {
1555     Label L_skip_barrier;
1556     __ mov_metadata(rscratch2, method->method_holder()); // InstanceKlass*
1557     __ clinit_barrier(rscratch2, rscratch1, &L_skip_barrier);
1558     __ far_jump(RuntimeAddress(SharedRuntime::get_handle_wrong_method_stub()));
1559 
1560     __ bind(L_skip_barrier);
1561   }
1562 
1563   // Generate stack overflow check
1564   __ bang_stack_with_offset(checked_cast<int>(StackOverflow::stack_shadow_zone_size()));
1565 
1566   // Generate a new frame for the wrapper.
1567   __ enter();
1568   // -2 because return address is already present and so is saved rfp
1569   __ sub(sp, sp, stack_size - 2*wordSize);
1570 
1571   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
1572   bs->nmethod_entry_barrier(masm);
1573 
1574   // Frame is now completed as far as size and linkage.
1575   int frame_complete = ((intptr_t)__ pc()) - start;
1576 
1577   // We use r20 as the oop handle for the receiver/klass
1578   // It is callee save so it survives the call to native
1579 
1580   const Register oop_handle_reg = r20;
1581 
1582   //
1583   // We immediately shuffle the arguments so that any vm call we have to
1584   // make from here on out (sync slow path, jvmti, etc.) we will have
1585   // captured the oops from our caller and have a valid oopMap for
1586   // them.
1587 
1588   // -----------------
1589   // The Grand Shuffle
1590 
1591   // The Java calling convention is either equal (linux) or denser (win64) than the
1592   // c calling convention. However the because of the jni_env argument the c calling
1593   // convention always has at least one more (and two for static) arguments than Java.
1594   // Therefore if we move the args from java -> c backwards then we will never have
1595   // a register->register conflict and we don't have to build a dependency graph
1596   // and figure out how to break any cycles.
1597   //
1598 
1599   // Record esp-based slot for receiver on stack for non-static methods
1600   int receiver_offset = -1;
1601 
1602   // This is a trick. We double the stack slots so we can claim
1603   // the oops in the caller's frame. Since we are sure to have
1604   // more args than the caller doubling is enough to make
1605   // sure we can capture all the incoming oop args from the
1606   // caller.
1607   //
1608   OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1609 
1610   // Mark location of rfp (someday)
1611   // map->set_callee_saved(VMRegImpl::stack2reg( stack_slots - 2), stack_slots * 2, 0, vmreg(rfp));
1612 
1613 
1614   int float_args = 0;
1615   int int_args = 0;
1616 
1617 #ifdef ASSERT
1618   bool reg_destroyed[RegisterImpl::number_of_registers];
1619   bool freg_destroyed[FloatRegisterImpl::number_of_registers];
1620   for ( int r = 0 ; r < RegisterImpl::number_of_registers ; r++ ) {
1621     reg_destroyed[r] = false;
1622   }
1623   for ( int f = 0 ; f < FloatRegisterImpl::number_of_registers ; f++ ) {
1624     freg_destroyed[f] = false;
1625   }
1626 
1627 #endif /* ASSERT */
1628 
1629   // For JNI natives the incoming and outgoing registers are offset upwards.
1630   GrowableArray<int> arg_order(2 * total_in_args);
1631   VMRegPair tmp_vmreg;
1632   tmp_vmreg.set2(r19->as_VMReg());
1633 
1634   for (int i = total_in_args - 1, c_arg = total_c_args - 1; i >= 0; i--, c_arg--) {
1635     arg_order.push(i);
1636     arg_order.push(c_arg);
1637   }
1638 
1639   int temploc = -1;
1640   for (int ai = 0; ai < arg_order.length(); ai += 2) {
1641     int i = arg_order.at(ai);
1642     int c_arg = arg_order.at(ai + 1);
1643     __ block_comment(err_msg("move %d -> %d", i, c_arg));
1644     assert(c_arg != -1 && i != -1, "wrong order");
1645 #ifdef ASSERT
1646     if (in_regs[i].first()->is_Register()) {
1647       assert(!reg_destroyed[in_regs[i].first()->as_Register()->encoding()], "destroyed reg!");
1648     } else if (in_regs[i].first()->is_FloatRegister()) {
1649       assert(!freg_destroyed[in_regs[i].first()->as_FloatRegister()->encoding()], "destroyed reg!");
1650     }
1651     if (out_regs[c_arg].first()->is_Register()) {
1652       reg_destroyed[out_regs[c_arg].first()->as_Register()->encoding()] = true;
1653     } else if (out_regs[c_arg].first()->is_FloatRegister()) {
1654       freg_destroyed[out_regs[c_arg].first()->as_FloatRegister()->encoding()] = true;
1655     }
1656 #endif /* ASSERT */
1657     switch (in_sig_bt[i]) {
1658       case T_ARRAY:
1659       case T_OBJECT:
1660         object_move(masm, map, oop_handle_offset, stack_slots, in_regs[i], out_regs[c_arg],
1661                     ((i == 0) && (!is_static)),
1662                     &receiver_offset);
1663         int_args++;
1664         break;
1665       case T_VOID:
1666         break;
1667 
1668       case T_FLOAT:
1669         float_move(masm, in_regs[i], out_regs[c_arg]);
1670         float_args++;
1671         break;
1672 
1673       case T_DOUBLE:
1674         assert( i + 1 < total_in_args &&
1675                 in_sig_bt[i + 1] == T_VOID &&
1676                 out_sig_bt[c_arg+1] == T_VOID, "bad arg list");
1677         double_move(masm, in_regs[i], out_regs[c_arg]);
1678         float_args++;
1679         break;
1680 
1681       case T_LONG :
1682         long_move(masm, in_regs[i], out_regs[c_arg]);
1683         int_args++;
1684         break;
1685 
1686       case T_ADDRESS: assert(false, "found T_ADDRESS in java args");
1687 
1688       default:
1689         move32_64(masm, in_regs[i], out_regs[c_arg]);
1690         int_args++;
1691     }
1692   }
1693 
1694   // point c_arg at the first arg that is already loaded in case we
1695   // need to spill before we call out
1696   int c_arg = total_c_args - total_in_args;
1697 
1698   // Pre-load a static method's oop into c_rarg1.
1699   if (method->is_static()) {
1700 
1701     //  load oop into a register
1702     __ movoop(c_rarg1,
1703               JNIHandles::make_local(method->method_holder()->java_mirror()),
1704               /*immediate*/true);
1705 
1706     // Now handlize the static class mirror it's known not-null.
1707     __ str(c_rarg1, Address(sp, klass_offset));
1708     map->set_oop(VMRegImpl::stack2reg(klass_slot_offset));
1709 
1710     // Now get the handle
1711     __ lea(c_rarg1, Address(sp, klass_offset));
1712     // and protect the arg if we must spill
1713     c_arg--;
1714   }
1715 
1716   // Change state to native (we save the return address in the thread, since it might not
1717   // be pushed on the stack when we do a stack traversal).
1718   // We use the same pc/oopMap repeatedly when we call out
1719 
1720   Label native_return;
1721   __ set_last_Java_frame(sp, noreg, native_return, rscratch1);
1722 
1723   Label dtrace_method_entry, dtrace_method_entry_done;
1724   {
1725     uint64_t offset;
1726     __ adrp(rscratch1, ExternalAddress((address)&DTraceMethodProbes), offset);
1727     __ ldrb(rscratch1, Address(rscratch1, offset));
1728     __ cbnzw(rscratch1, dtrace_method_entry);
1729     __ bind(dtrace_method_entry_done);
1730   }
1731 
1732   // RedefineClasses() tracing support for obsolete method entry
1733   if (log_is_enabled(Trace, redefine, class, obsolete)) {
1734     // protect the args we've loaded
1735     save_args(masm, total_c_args, c_arg, out_regs);
1736     __ mov_metadata(c_rarg1, method());
1737     __ call_VM_leaf(
1738       CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
1739       rthread, c_rarg1);
1740     restore_args(masm, total_c_args, c_arg, out_regs);
1741   }
1742 
1743   // Lock a synchronized method
1744 
1745   // Register definitions used by locking and unlocking
1746 
1747   const Register swap_reg = r0;
1748   const Register obj_reg  = r19;  // Will contain the oop
1749   const Register lock_reg = r13;  // Address of compiler lock object (BasicLock)
1750   const Register old_hdr  = r13;  // value of old header at unlock time
1751   const Register tmp = lr;
1752 
1753   Label slow_path_lock;
1754   Label lock_done;
1755 
1756   if (method->is_synchronized()) {
1757 
1758     const int mark_word_offset = BasicLock::displaced_header_offset_in_bytes();
1759 
1760     // Get the handle (the 2nd argument)
1761     __ mov(oop_handle_reg, c_rarg1);
1762 
1763     // Get address of the box
1764 
1765     __ lea(lock_reg, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
1766 
1767     // Load the oop from the handle
1768     __ ldr(obj_reg, Address(oop_handle_reg, 0));
1769 
1770     // Load (object->mark() | 1) into swap_reg %r0
1771     __ ldr(rscratch1, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1772     __ orr(swap_reg, rscratch1, 1);
1773 
1774     // Save (object->mark() | 1) into BasicLock's displaced header
1775     __ str(swap_reg, Address(lock_reg, mark_word_offset));
1776 
1777     // src -> dest iff dest == r0 else r0 <- dest
1778     { Label here;
1779       __ cmpxchg_obj_header(r0, lock_reg, obj_reg, rscratch1, lock_done, /*fallthrough*/NULL);
1780     }
1781 
1782     // Hmm should this move to the slow path code area???
1783 
1784     // Test if the oopMark is an obvious stack pointer, i.e.,
1785     //  1) (mark & 3) == 0, and
1786     //  2) sp <= mark < mark + os::pagesize()
1787     // These 3 tests can be done by evaluating the following
1788     // expression: ((mark - sp) & (3 - os::vm_page_size())),
1789     // assuming both stack pointer and pagesize have their
1790     // least significant 2 bits clear.
1791     // NOTE: the oopMark is in swap_reg %r0 as the result of cmpxchg
1792 
1793     __ sub(swap_reg, sp, swap_reg);
1794     __ neg(swap_reg, swap_reg);
1795     __ ands(swap_reg, swap_reg, 3 - os::vm_page_size());
1796 
1797     // Save the test result, for recursive case, the result is zero
1798     __ str(swap_reg, Address(lock_reg, mark_word_offset));
1799     __ br(Assembler::NE, slow_path_lock);
1800 
1801     // Slow path will re-enter here
1802 
1803     __ bind(lock_done);
1804   }
1805 
1806 
1807   // Finally just about ready to make the JNI call
1808 
1809   // get JNIEnv* which is first argument to native
1810   __ lea(c_rarg0, Address(rthread, in_bytes(JavaThread::jni_environment_offset())));
1811 
1812   // Now set thread in native
1813   __ mov(rscratch1, _thread_in_native);
1814   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
1815   __ stlrw(rscratch1, rscratch2);
1816 
1817   rt_call(masm, native_func);
1818 
1819   __ bind(native_return);
1820 
1821   intptr_t return_pc = (intptr_t) __ pc();
1822   oop_maps->add_gc_map(return_pc - start, map);
1823 
1824   // Unpack native results.
1825   switch (ret_type) {
1826   case T_BOOLEAN: __ c2bool(r0);                     break;
1827   case T_CHAR   : __ ubfx(r0, r0, 0, 16);            break;
1828   case T_BYTE   : __ sbfx(r0, r0, 0, 8);             break;
1829   case T_SHORT  : __ sbfx(r0, r0, 0, 16);            break;
1830   case T_INT    : __ sbfx(r0, r0, 0, 32);            break;
1831   case T_DOUBLE :
1832   case T_FLOAT  :
1833     // Result is in v0 we'll save as needed
1834     break;
1835   case T_ARRAY:                 // Really a handle
1836   case T_OBJECT:                // Really a handle
1837       break; // can't de-handlize until after safepoint check
1838   case T_VOID: break;
1839   case T_LONG: break;
1840   default       : ShouldNotReachHere();
1841   }
1842 
1843   Label safepoint_in_progress, safepoint_in_progress_done;
1844   Label after_transition;
1845 
1846   // Switch thread to "native transition" state before reading the synchronization state.
1847   // This additional state is necessary because reading and testing the synchronization
1848   // state is not atomic w.r.t. GC, as this scenario demonstrates:
1849   //     Java thread A, in _thread_in_native state, loads _not_synchronized and is preempted.
1850   //     VM thread changes sync state to synchronizing and suspends threads for GC.
1851   //     Thread A is resumed to finish this native method, but doesn't block here since it
1852   //     didn't see any synchronization is progress, and escapes.
1853   __ mov(rscratch1, _thread_in_native_trans);
1854 
1855   __ strw(rscratch1, Address(rthread, JavaThread::thread_state_offset()));
1856 
1857   // Force this write out before the read below
1858   __ dmb(Assembler::ISH);
1859 
1860   __ verify_sve_vector_length();
1861 
1862   // Check for safepoint operation in progress and/or pending suspend requests.
1863   {
1864     // We need an acquire here to ensure that any subsequent load of the
1865     // global SafepointSynchronize::_state flag is ordered after this load
1866     // of the thread-local polling word.  We don't want this poll to
1867     // return false (i.e. not safepointing) and a later poll of the global
1868     // SafepointSynchronize::_state spuriously to return true.
1869     //
1870     // This is to avoid a race when we're in a native->Java transition
1871     // racing the code which wakes up from a safepoint.
1872 
1873     __ safepoint_poll(safepoint_in_progress, true /* at_return */, true /* acquire */, false /* in_nmethod */);
1874     __ ldrw(rscratch1, Address(rthread, JavaThread::suspend_flags_offset()));
1875     __ cbnzw(rscratch1, safepoint_in_progress);
1876     __ bind(safepoint_in_progress_done);
1877   }
1878 
1879   // change thread state
1880   __ mov(rscratch1, _thread_in_Java);
1881   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
1882   __ stlrw(rscratch1, rscratch2);
1883   __ bind(after_transition);
1884 
1885   Label reguard;
1886   Label reguard_done;
1887   __ ldrb(rscratch1, Address(rthread, JavaThread::stack_guard_state_offset()));
1888   __ cmpw(rscratch1, StackOverflow::stack_guard_yellow_reserved_disabled);
1889   __ br(Assembler::EQ, reguard);
1890   __ bind(reguard_done);
1891 
1892   // native result if any is live
1893 
1894   // Unlock
1895   Label unlock_done;
1896   Label slow_path_unlock;
1897   if (method->is_synchronized()) {
1898 
1899     // Get locked oop from the handle we passed to jni
1900     __ ldr(obj_reg, Address(oop_handle_reg, 0));
1901 
1902     Label done;
1903     // Simple recursive lock?
1904 
1905     __ ldr(rscratch1, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
1906     __ cbz(rscratch1, done);
1907 
1908     // Must save r0 if if it is live now because cmpxchg must use it
1909     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
1910       save_native_result(masm, ret_type, stack_slots);
1911     }
1912 
1913 
1914     // get address of the stack lock
1915     __ lea(r0, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
1916     //  get old displaced header
1917     __ ldr(old_hdr, Address(r0, 0));
1918 
1919     // Atomic swap old header if oop still contains the stack lock
1920     Label succeed;
1921     __ cmpxchg_obj_header(r0, old_hdr, obj_reg, rscratch1, succeed, &slow_path_unlock);
1922     __ bind(succeed);
1923 
1924     // slow path re-enters here
1925     __ bind(unlock_done);
1926     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
1927       restore_native_result(masm, ret_type, stack_slots);
1928     }
1929 
1930     __ bind(done);
1931   }
1932 
1933   Label dtrace_method_exit, dtrace_method_exit_done;
1934   {
1935     uint64_t offset;
1936     __ adrp(rscratch1, ExternalAddress((address)&DTraceMethodProbes), offset);
1937     __ ldrb(rscratch1, Address(rscratch1, offset));
1938     __ cbnzw(rscratch1, dtrace_method_exit);
1939     __ bind(dtrace_method_exit_done);
1940   }
1941 
1942   __ reset_last_Java_frame(false);
1943 
1944   // Unbox oop result, e.g. JNIHandles::resolve result.
1945   if (is_reference_type(ret_type)) {
1946     __ resolve_jobject(r0, rthread, rscratch2);
1947   }
1948 
1949   if (CheckJNICalls) {
1950     // clear_pending_jni_exception_check
1951     __ str(zr, Address(rthread, JavaThread::pending_jni_exception_check_fn_offset()));
1952   }
1953 
1954   // reset handle block
1955   __ ldr(r2, Address(rthread, JavaThread::active_handles_offset()));
1956   __ str(zr, Address(r2, JNIHandleBlock::top_offset_in_bytes()));
1957 
1958   __ leave();
1959 
1960   // Any exception pending?
1961   __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
1962   __ cbnz(rscratch1, exception_pending);
1963 
1964   // We're done
1965   __ ret(lr);
1966 
1967   // Unexpected paths are out of line and go here
1968 
1969   // forward the exception
1970   __ bind(exception_pending);
1971 
1972   // and forward the exception
1973   __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
1974 
1975   // Slow path locking & unlocking
1976   if (method->is_synchronized()) {
1977 
1978     __ block_comment("Slow path lock {");
1979     __ bind(slow_path_lock);
1980 
1981     // has last_Java_frame setup. No exceptions so do vanilla call not call_VM
1982     // args are (oop obj, BasicLock* lock, JavaThread* thread)
1983 
1984     // protect the args we've loaded
1985     save_args(masm, total_c_args, c_arg, out_regs);
1986 
1987     __ mov(c_rarg0, obj_reg);
1988     __ mov(c_rarg1, lock_reg);
1989     __ mov(c_rarg2, rthread);
1990 
1991     // Not a leaf but we have last_Java_frame setup as we want
1992     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_locking_C), 3);
1993     restore_args(masm, total_c_args, c_arg, out_regs);
1994 
1995 #ifdef ASSERT
1996     { Label L;
1997       __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
1998       __ cbz(rscratch1, L);
1999       __ stop("no pending exception allowed on exit from monitorenter");
2000       __ bind(L);
2001     }
2002 #endif
2003     __ b(lock_done);
2004 
2005     __ block_comment("} Slow path lock");
2006 
2007     __ block_comment("Slow path unlock {");
2008     __ bind(slow_path_unlock);
2009 
2010     // If we haven't already saved the native result we must save it now as xmm registers
2011     // are still exposed.
2012 
2013     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2014       save_native_result(masm, ret_type, stack_slots);
2015     }
2016 
2017     __ mov(c_rarg2, rthread);
2018     __ lea(c_rarg1, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
2019     __ mov(c_rarg0, obj_reg);
2020 
2021     // Save pending exception around call to VM (which contains an EXCEPTION_MARK)
2022     // NOTE that obj_reg == r19 currently
2023     __ ldr(r19, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2024     __ str(zr, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2025 
2026     rt_call(masm, CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C));
2027 
2028 #ifdef ASSERT
2029     {
2030       Label L;
2031       __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2032       __ cbz(rscratch1, L);
2033       __ stop("no pending exception allowed on exit complete_monitor_unlocking_C");
2034       __ bind(L);
2035     }
2036 #endif /* ASSERT */
2037 
2038     __ str(r19, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2039 
2040     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2041       restore_native_result(masm, ret_type, stack_slots);
2042     }
2043     __ b(unlock_done);
2044 
2045     __ block_comment("} Slow path unlock");
2046 
2047   } // synchronized
2048 
2049   // SLOW PATH Reguard the stack if needed
2050 
2051   __ bind(reguard);
2052   save_native_result(masm, ret_type, stack_slots);
2053   rt_call(masm, CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages));
2054   restore_native_result(masm, ret_type, stack_slots);
2055   // and continue
2056   __ b(reguard_done);
2057 
2058   // SLOW PATH safepoint
2059   {
2060     __ block_comment("safepoint {");
2061     __ bind(safepoint_in_progress);
2062 
2063     // Don't use call_VM as it will see a possible pending exception and forward it
2064     // and never return here preventing us from clearing _last_native_pc down below.
2065     //
2066     save_native_result(masm, ret_type, stack_slots);
2067     __ mov(c_rarg0, rthread);
2068 #ifndef PRODUCT
2069   assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
2070 #endif
2071     __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans)));
2072     __ blr(rscratch1);
2073 
2074     // Restore any method result value
2075     restore_native_result(masm, ret_type, stack_slots);
2076 
2077     __ b(safepoint_in_progress_done);
2078     __ block_comment("} safepoint");
2079   }
2080 
2081   // SLOW PATH dtrace support
2082   {
2083     __ block_comment("dtrace entry {");
2084     __ bind(dtrace_method_entry);
2085 
2086     // We have all of the arguments setup at this point. We must not touch any register
2087     // argument registers at this point (what if we save/restore them there are no oop?
2088 
2089     save_args(masm, total_c_args, c_arg, out_regs);
2090     __ mov_metadata(c_rarg1, method());
2091     __ call_VM_leaf(
2092       CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry),
2093       rthread, c_rarg1);
2094     restore_args(masm, total_c_args, c_arg, out_regs);
2095     __ b(dtrace_method_entry_done);
2096     __ block_comment("} dtrace entry");
2097   }
2098 
2099   {
2100     __ block_comment("dtrace exit {");
2101     __ bind(dtrace_method_exit);
2102     save_native_result(masm, ret_type, stack_slots);
2103     __ mov_metadata(c_rarg1, method());
2104     __ call_VM_leaf(
2105          CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit),
2106          rthread, c_rarg1);
2107     restore_native_result(masm, ret_type, stack_slots);
2108     __ b(dtrace_method_exit_done);
2109     __ block_comment("} dtrace exit");
2110   }
2111 
2112 
2113   __ flush();
2114 
2115   nmethod *nm = nmethod::new_native_nmethod(method,
2116                                             compile_id,
2117                                             masm->code(),
2118                                             vep_offset,
2119                                             frame_complete,
2120                                             stack_slots / VMRegImpl::slots_per_word,
2121                                             (is_static ? in_ByteSize(klass_offset) : in_ByteSize(receiver_offset)),
2122                                             in_ByteSize(lock_slot_offset*VMRegImpl::stack_slot_size),
2123                                             oop_maps);
2124 
2125   return nm;
2126 }
2127 
2128 // this function returns the adjust size (in number of words) to a c2i adapter
2129 // activation for use during deoptimization
2130 int Deoptimization::last_frame_adjust(int callee_parameters, int callee_locals) {
2131   assert(callee_locals >= callee_parameters,
2132           "test and remove; got more parms than locals");
2133   if (callee_locals < callee_parameters)
2134     return 0;                   // No adjustment for negative locals
2135   int diff = (callee_locals - callee_parameters) * Interpreter::stackElementWords;
2136   // diff is counted in stack words
2137   return align_up(diff, 2);
2138 }
2139 
2140 
2141 //------------------------------generate_deopt_blob----------------------------
2142 void SharedRuntime::generate_deopt_blob() {
2143   // Allocate space for the code
2144   ResourceMark rm;
2145   // Setup code generation tools
2146   int pad = 0;
2147 #if INCLUDE_JVMCI
2148   if (EnableJVMCI) {
2149     pad += 512; // Increase the buffer size when compiling for JVMCI
2150   }
2151 #endif
2152   CodeBuffer buffer("deopt_blob", 2048+pad, 1024);
2153   MacroAssembler* masm = new MacroAssembler(&buffer);
2154   int frame_size_in_words;
2155   OopMap* map = NULL;
2156   OopMapSet *oop_maps = new OopMapSet();
2157   RegisterSaver reg_save(COMPILER2_OR_JVMCI != 0);
2158 
2159   // -------------
2160   // This code enters when returning to a de-optimized nmethod.  A return
2161   // address has been pushed on the the stack, and return values are in
2162   // registers.
2163   // If we are doing a normal deopt then we were called from the patched
2164   // nmethod from the point we returned to the nmethod. So the return
2165   // address on the stack is wrong by NativeCall::instruction_size
2166   // We will adjust the value so it looks like we have the original return
2167   // address on the stack (like when we eagerly deoptimized).
2168   // In the case of an exception pending when deoptimizing, we enter
2169   // with a return address on the stack that points after the call we patched
2170   // into the exception handler. We have the following register state from,
2171   // e.g., the forward exception stub (see stubGenerator_x86_64.cpp).
2172   //    r0: exception oop
2173   //    r19: exception handler
2174   //    r3: throwing pc
2175   // So in this case we simply jam r3 into the useless return address and
2176   // the stack looks just like we want.
2177   //
2178   // At this point we need to de-opt.  We save the argument return
2179   // registers.  We call the first C routine, fetch_unroll_info().  This
2180   // routine captures the return values and returns a structure which
2181   // describes the current frame size and the sizes of all replacement frames.
2182   // The current frame is compiled code and may contain many inlined
2183   // functions, each with their own JVM state.  We pop the current frame, then
2184   // push all the new frames.  Then we call the C routine unpack_frames() to
2185   // populate these frames.  Finally unpack_frames() returns us the new target
2186   // address.  Notice that callee-save registers are BLOWN here; they have
2187   // already been captured in the vframeArray at the time the return PC was
2188   // patched.
2189   address start = __ pc();
2190   Label cont;
2191 
2192   // Prolog for non exception case!
2193 
2194   // Save everything in sight.
2195   map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2196 
2197   // Normal deoptimization.  Save exec mode for unpack_frames.
2198   __ movw(rcpool, Deoptimization::Unpack_deopt); // callee-saved
2199   __ b(cont);
2200 
2201   int reexecute_offset = __ pc() - start;
2202 #if INCLUDE_JVMCI && !defined(COMPILER1)
2203   if (EnableJVMCI && UseJVMCICompiler) {
2204     // JVMCI does not use this kind of deoptimization
2205     __ should_not_reach_here();
2206   }
2207 #endif
2208 
2209   // Reexecute case
2210   // return address is the pc describes what bci to do re-execute at
2211 
2212   // No need to update map as each call to save_live_registers will produce identical oopmap
2213   (void) reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2214 
2215   __ movw(rcpool, Deoptimization::Unpack_reexecute); // callee-saved
2216   __ b(cont);
2217 
2218 #if INCLUDE_JVMCI
2219   Label after_fetch_unroll_info_call;
2220   int implicit_exception_uncommon_trap_offset = 0;
2221   int uncommon_trap_offset = 0;
2222 
2223   if (EnableJVMCI) {
2224     implicit_exception_uncommon_trap_offset = __ pc() - start;
2225 
2226     __ ldr(lr, Address(rthread, in_bytes(JavaThread::jvmci_implicit_exception_pc_offset())));
2227     __ str(zr, Address(rthread, in_bytes(JavaThread::jvmci_implicit_exception_pc_offset())));
2228 
2229     uncommon_trap_offset = __ pc() - start;
2230 
2231     // Save everything in sight.
2232     reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2233     // fetch_unroll_info needs to call last_java_frame()
2234     Label retaddr;
2235     __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2236 
2237     __ ldrw(c_rarg1, Address(rthread, in_bytes(JavaThread::pending_deoptimization_offset())));
2238     __ movw(rscratch1, -1);
2239     __ strw(rscratch1, Address(rthread, in_bytes(JavaThread::pending_deoptimization_offset())));
2240 
2241     __ movw(rcpool, (int32_t)Deoptimization::Unpack_reexecute);
2242     __ mov(c_rarg0, rthread);
2243     __ movw(c_rarg2, rcpool); // exec mode
2244     __ lea(rscratch1,
2245            RuntimeAddress(CAST_FROM_FN_PTR(address,
2246                                            Deoptimization::uncommon_trap)));
2247     __ blr(rscratch1);
2248     __ bind(retaddr);
2249     oop_maps->add_gc_map( __ pc()-start, map->deep_copy());
2250 
2251     __ reset_last_Java_frame(false);
2252 
2253     __ b(after_fetch_unroll_info_call);
2254   } // EnableJVMCI
2255 #endif // INCLUDE_JVMCI
2256 
2257   int exception_offset = __ pc() - start;
2258 
2259   // Prolog for exception case
2260 
2261   // all registers are dead at this entry point, except for r0, and
2262   // r3 which contain the exception oop and exception pc
2263   // respectively.  Set them in TLS and fall thru to the
2264   // unpack_with_exception_in_tls entry point.
2265 
2266   __ str(r3, Address(rthread, JavaThread::exception_pc_offset()));
2267   __ str(r0, Address(rthread, JavaThread::exception_oop_offset()));
2268 
2269   int exception_in_tls_offset = __ pc() - start;
2270 
2271   // new implementation because exception oop is now passed in JavaThread
2272 
2273   // Prolog for exception case
2274   // All registers must be preserved because they might be used by LinearScan
2275   // Exceptiop oop and throwing PC are passed in JavaThread
2276   // tos: stack at point of call to method that threw the exception (i.e. only
2277   // args are on the stack, no return address)
2278 
2279   // The return address pushed by save_live_registers will be patched
2280   // later with the throwing pc. The correct value is not available
2281   // now because loading it from memory would destroy registers.
2282 
2283   // NB: The SP at this point must be the SP of the method that is
2284   // being deoptimized.  Deoptimization assumes that the frame created
2285   // here by save_live_registers is immediately below the method's SP.
2286   // This is a somewhat fragile mechanism.
2287 
2288   // Save everything in sight.
2289   map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2290 
2291   // Now it is safe to overwrite any register
2292 
2293   // Deopt during an exception.  Save exec mode for unpack_frames.
2294   __ mov(rcpool, Deoptimization::Unpack_exception); // callee-saved
2295 
2296   // load throwing pc from JavaThread and patch it as the return address
2297   // of the current frame. Then clear the field in JavaThread
2298 
2299   __ ldr(r3, Address(rthread, JavaThread::exception_pc_offset()));
2300   __ str(r3, Address(rfp, wordSize));
2301   __ str(zr, Address(rthread, JavaThread::exception_pc_offset()));
2302 
2303 #ifdef ASSERT
2304   // verify that there is really an exception oop in JavaThread
2305   __ ldr(r0, Address(rthread, JavaThread::exception_oop_offset()));
2306   __ verify_oop(r0);
2307 
2308   // verify that there is no pending exception
2309   Label no_pending_exception;
2310   __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
2311   __ cbz(rscratch1, no_pending_exception);
2312   __ stop("must not have pending exception here");
2313   __ bind(no_pending_exception);
2314 #endif
2315 
2316   __ bind(cont);
2317 
2318   // Call C code.  Need thread and this frame, but NOT official VM entry
2319   // crud.  We cannot block on this call, no GC can happen.
2320   //
2321   // UnrollBlock* fetch_unroll_info(JavaThread* thread)
2322 
2323   // fetch_unroll_info needs to call last_java_frame().
2324 
2325   Label retaddr;
2326   __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2327 #ifdef ASSERT0
2328   { Label L;
2329     __ ldr(rscratch1, Address(rthread,
2330                               JavaThread::last_Java_fp_offset()));
2331     __ cbz(rscratch1, L);
2332     __ stop("SharedRuntime::generate_deopt_blob: last_Java_fp not cleared");
2333     __ bind(L);
2334   }
2335 #endif // ASSERT
2336   __ mov(c_rarg0, rthread);
2337   __ mov(c_rarg1, rcpool);
2338   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::fetch_unroll_info)));
2339   __ blr(rscratch1);
2340   __ bind(retaddr);
2341 
2342   // Need to have an oopmap that tells fetch_unroll_info where to
2343   // find any register it might need.
2344   oop_maps->add_gc_map(__ pc() - start, map);
2345 
2346   __ reset_last_Java_frame(false);
2347 
2348 #if INCLUDE_JVMCI
2349   if (EnableJVMCI) {
2350     __ bind(after_fetch_unroll_info_call);
2351   }
2352 #endif
2353 
2354   // Load UnrollBlock* into r5
2355   __ mov(r5, r0);
2356 
2357   __ ldrw(rcpool, Address(r5, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes()));
2358    Label noException;
2359   __ cmpw(rcpool, Deoptimization::Unpack_exception);   // Was exception pending?
2360   __ br(Assembler::NE, noException);
2361   __ ldr(r0, Address(rthread, JavaThread::exception_oop_offset()));
2362   // QQQ this is useless it was NULL above
2363   __ ldr(r3, Address(rthread, JavaThread::exception_pc_offset()));
2364   __ str(zr, Address(rthread, JavaThread::exception_oop_offset()));
2365   __ str(zr, Address(rthread, JavaThread::exception_pc_offset()));
2366 
2367   __ verify_oop(r0);
2368 
2369   // Overwrite the result registers with the exception results.
2370   __ str(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2371   // I think this is useless
2372   // __ str(r3, Address(sp, RegisterSaver::r3_offset_in_bytes()));
2373 
2374   __ bind(noException);
2375 
2376   // Only register save data is on the stack.
2377   // Now restore the result registers.  Everything else is either dead
2378   // or captured in the vframeArray.
2379 
2380   // Restore fp result register
2381   __ ldrd(v0, Address(sp, reg_save.v0_offset_in_bytes()));
2382   // Restore integer result register
2383   __ ldr(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2384 
2385   // Pop all of the register save area off the stack
2386   __ add(sp, sp, frame_size_in_words * wordSize);
2387 
2388   // All of the register save area has been popped of the stack. Only the
2389   // return address remains.
2390 
2391   // Pop all the frames we must move/replace.
2392   //
2393   // Frame picture (youngest to oldest)
2394   // 1: self-frame (no frame link)
2395   // 2: deopting frame  (no frame link)
2396   // 3: caller of deopting frame (could be compiled/interpreted).
2397   //
2398   // Note: by leaving the return address of self-frame on the stack
2399   // and using the size of frame 2 to adjust the stack
2400   // when we are done the return to frame 3 will still be on the stack.
2401 
2402   // Pop deoptimized frame
2403   __ ldrw(r2, Address(r5, Deoptimization::UnrollBlock::size_of_deoptimized_frame_offset_in_bytes()));
2404   __ sub(r2, r2, 2 * wordSize);
2405   __ add(sp, sp, r2);
2406   __ ldp(rfp, lr, __ post(sp, 2 * wordSize));
2407   // LR should now be the return address to the caller (3)
2408 
2409 #ifdef ASSERT
2410   // Compilers generate code that bang the stack by as much as the
2411   // interpreter would need. So this stack banging should never
2412   // trigger a fault. Verify that it does not on non product builds.
2413   __ ldrw(r19, Address(r5, Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes()));
2414   __ bang_stack_size(r19, r2);
2415 #endif
2416   // Load address of array of frame pcs into r2
2417   __ ldr(r2, Address(r5, Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2418 
2419   // Trash the old pc
2420   // __ addptr(sp, wordSize);  FIXME ????
2421 
2422   // Load address of array of frame sizes into r4
2423   __ ldr(r4, Address(r5, Deoptimization::UnrollBlock::frame_sizes_offset_in_bytes()));
2424 
2425   // Load counter into r3
2426   __ ldrw(r3, Address(r5, Deoptimization::UnrollBlock::number_of_frames_offset_in_bytes()));
2427 
2428   // Now adjust the caller's stack to make up for the extra locals
2429   // but record the original sp so that we can save it in the skeletal interpreter
2430   // frame and the stack walking of interpreter_sender will get the unextended sp
2431   // value and not the "real" sp value.
2432 
2433   const Register sender_sp = r6;
2434 
2435   __ mov(sender_sp, sp);
2436   __ ldrw(r19, Address(r5,
2437                        Deoptimization::UnrollBlock::
2438                        caller_adjustment_offset_in_bytes()));
2439   __ sub(sp, sp, r19);
2440 
2441   // Push interpreter frames in a loop
2442   __ mov(rscratch1, (uint64_t)0xDEADDEAD);        // Make a recognizable pattern
2443   __ mov(rscratch2, rscratch1);
2444   Label loop;
2445   __ bind(loop);
2446   __ ldr(r19, Address(__ post(r4, wordSize)));          // Load frame size
2447   __ sub(r19, r19, 2*wordSize);           // We'll push pc and fp by hand
2448   __ ldr(lr, Address(__ post(r2, wordSize)));  // Load pc
2449   __ enter();                           // Save old & set new fp
2450   __ sub(sp, sp, r19);                  // Prolog
2451   // This value is corrected by layout_activation_impl
2452   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
2453   __ str(sender_sp, Address(rfp, frame::interpreter_frame_sender_sp_offset * wordSize)); // Make it walkable
2454   __ mov(sender_sp, sp);               // Pass sender_sp to next frame
2455   __ sub(r3, r3, 1);                   // Decrement counter
2456   __ cbnz(r3, loop);
2457 
2458     // Re-push self-frame
2459   __ ldr(lr, Address(r2));
2460   __ enter();
2461 
2462   // Allocate a full sized register save area.  We subtract 2 because
2463   // enter() just pushed 2 words
2464   __ sub(sp, sp, (frame_size_in_words - 2) * wordSize);
2465 
2466   // Restore frame locals after moving the frame
2467   __ strd(v0, Address(sp, reg_save.v0_offset_in_bytes()));
2468   __ str(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2469 
2470   // Call C code.  Need thread but NOT official VM entry
2471   // crud.  We cannot block on this call, no GC can happen.  Call should
2472   // restore return values to their stack-slots with the new SP.
2473   //
2474   // void Deoptimization::unpack_frames(JavaThread* thread, int exec_mode)
2475 
2476   // Use rfp because the frames look interpreted now
2477   // Don't need the precise return PC here, just precise enough to point into this code blob.
2478   address the_pc = __ pc();
2479   __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
2480 
2481   __ mov(c_rarg0, rthread);
2482   __ movw(c_rarg1, rcpool); // second arg: exec_mode
2483   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2484   __ blr(rscratch1);
2485 
2486   // Set an oopmap for the call site
2487   // Use the same PC we used for the last java frame
2488   oop_maps->add_gc_map(the_pc - start,
2489                        new OopMap( frame_size_in_words, 0 ));
2490 
2491   // Clear fp AND pc
2492   __ reset_last_Java_frame(true);
2493 
2494   // Collect return values
2495   __ ldrd(v0, Address(sp, reg_save.v0_offset_in_bytes()));
2496   __ ldr(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2497   // I think this is useless (throwing pc?)
2498   // __ ldr(r3, Address(sp, RegisterSaver::r3_offset_in_bytes()));
2499 
2500   // Pop self-frame.
2501   __ leave();                           // Epilog
2502 
2503   // Jump to interpreter
2504   __ ret(lr);
2505 
2506   // Make sure all code is generated
2507   masm->flush();
2508 
2509   _deopt_blob = DeoptimizationBlob::create(&buffer, oop_maps, 0, exception_offset, reexecute_offset, frame_size_in_words);
2510   _deopt_blob->set_unpack_with_exception_in_tls_offset(exception_in_tls_offset);
2511 #if INCLUDE_JVMCI
2512   if (EnableJVMCI) {
2513     _deopt_blob->set_uncommon_trap_offset(uncommon_trap_offset);
2514     _deopt_blob->set_implicit_exception_uncommon_trap_offset(implicit_exception_uncommon_trap_offset);
2515   }
2516 #endif
2517 }
2518 
2519 // Number of stack slots between incoming argument block and the start of
2520 // a new frame.  The PROLOG must add this many slots to the stack.  The
2521 // EPILOG must remove this many slots. aarch64 needs two slots for
2522 // return address and fp.
2523 // TODO think this is correct but check
2524 uint SharedRuntime::in_preserve_stack_slots() {
2525   return 4;
2526 }
2527 
2528 uint SharedRuntime::out_preserve_stack_slots() {
2529   return 0;
2530 }
2531 
2532 #ifdef COMPILER2
2533 //------------------------------generate_uncommon_trap_blob--------------------
2534 void SharedRuntime::generate_uncommon_trap_blob() {
2535   // Allocate space for the code
2536   ResourceMark rm;
2537   // Setup code generation tools
2538   CodeBuffer buffer("uncommon_trap_blob", 2048, 1024);
2539   MacroAssembler* masm = new MacroAssembler(&buffer);
2540 
2541   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
2542 
2543   address start = __ pc();
2544 
2545   // Push self-frame.  We get here with a return address in LR
2546   // and sp should be 16 byte aligned
2547   // push rfp and retaddr by hand
2548   __ stp(rfp, lr, Address(__ pre(sp, -2 * wordSize)));
2549   // we don't expect an arg reg save area
2550 #ifndef PRODUCT
2551   assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
2552 #endif
2553   // compiler left unloaded_class_index in j_rarg0 move to where the
2554   // runtime expects it.
2555   if (c_rarg1 != j_rarg0) {
2556     __ movw(c_rarg1, j_rarg0);
2557   }
2558 
2559   // we need to set the past SP to the stack pointer of the stub frame
2560   // and the pc to the address where this runtime call will return
2561   // although actually any pc in this code blob will do).
2562   Label retaddr;
2563   __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2564 
2565   // Call C code.  Need thread but NOT official VM entry
2566   // crud.  We cannot block on this call, no GC can happen.  Call should
2567   // capture callee-saved registers as well as return values.
2568   // Thread is in rdi already.
2569   //
2570   // UnrollBlock* uncommon_trap(JavaThread* thread, jint unloaded_class_index);
2571   //
2572   // n.b. 2 gp args, 0 fp args, integral return type
2573 
2574   __ mov(c_rarg0, rthread);
2575   __ movw(c_rarg2, (unsigned)Deoptimization::Unpack_uncommon_trap);
2576   __ lea(rscratch1,
2577          RuntimeAddress(CAST_FROM_FN_PTR(address,
2578                                          Deoptimization::uncommon_trap)));
2579   __ blr(rscratch1);
2580   __ bind(retaddr);
2581 
2582   // Set an oopmap for the call site
2583   OopMapSet* oop_maps = new OopMapSet();
2584   OopMap* map = new OopMap(SimpleRuntimeFrame::framesize, 0);
2585 
2586   // location of rfp is known implicitly by the frame sender code
2587 
2588   oop_maps->add_gc_map(__ pc() - start, map);
2589 
2590   __ reset_last_Java_frame(false);
2591 
2592   // move UnrollBlock* into r4
2593   __ mov(r4, r0);
2594 
2595 #ifdef ASSERT
2596   { Label L;
2597     __ ldrw(rscratch1, Address(r4, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes()));
2598     __ cmpw(rscratch1, (unsigned)Deoptimization::Unpack_uncommon_trap);
2599     __ br(Assembler::EQ, L);
2600     __ stop("SharedRuntime::generate_deopt_blob: last_Java_fp not cleared");
2601     __ bind(L);
2602   }
2603 #endif
2604 
2605   // Pop all the frames we must move/replace.
2606   //
2607   // Frame picture (youngest to oldest)
2608   // 1: self-frame (no frame link)
2609   // 2: deopting frame  (no frame link)
2610   // 3: caller of deopting frame (could be compiled/interpreted).
2611 
2612   // Pop self-frame.  We have no frame, and must rely only on r0 and sp.
2613   __ add(sp, sp, (SimpleRuntimeFrame::framesize) << LogBytesPerInt); // Epilog!
2614 
2615   // Pop deoptimized frame (int)
2616   __ ldrw(r2, Address(r4,
2617                       Deoptimization::UnrollBlock::
2618                       size_of_deoptimized_frame_offset_in_bytes()));
2619   __ sub(r2, r2, 2 * wordSize);
2620   __ add(sp, sp, r2);
2621   __ ldp(rfp, lr, __ post(sp, 2 * wordSize));
2622   // LR should now be the return address to the caller (3) frame
2623 
2624 #ifdef ASSERT
2625   // Compilers generate code that bang the stack by as much as the
2626   // interpreter would need. So this stack banging should never
2627   // trigger a fault. Verify that it does not on non product builds.
2628   __ ldrw(r1, Address(r4,
2629                       Deoptimization::UnrollBlock::
2630                       total_frame_sizes_offset_in_bytes()));
2631   __ bang_stack_size(r1, r2);
2632 #endif
2633 
2634   // Load address of array of frame pcs into r2 (address*)
2635   __ ldr(r2, Address(r4,
2636                      Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2637 
2638   // Load address of array of frame sizes into r5 (intptr_t*)
2639   __ ldr(r5, Address(r4,
2640                      Deoptimization::UnrollBlock::
2641                      frame_sizes_offset_in_bytes()));
2642 
2643   // Counter
2644   __ ldrw(r3, Address(r4,
2645                       Deoptimization::UnrollBlock::
2646                       number_of_frames_offset_in_bytes())); // (int)
2647 
2648   // Now adjust the caller's stack to make up for the extra locals but
2649   // record the original sp so that we can save it in the skeletal
2650   // interpreter frame and the stack walking of interpreter_sender
2651   // will get the unextended sp value and not the "real" sp value.
2652 
2653   const Register sender_sp = r8;
2654 
2655   __ mov(sender_sp, sp);
2656   __ ldrw(r1, Address(r4,
2657                       Deoptimization::UnrollBlock::
2658                       caller_adjustment_offset_in_bytes())); // (int)
2659   __ sub(sp, sp, r1);
2660 
2661   // Push interpreter frames in a loop
2662   Label loop;
2663   __ bind(loop);
2664   __ ldr(r1, Address(r5, 0));       // Load frame size
2665   __ sub(r1, r1, 2 * wordSize);     // We'll push pc and rfp by hand
2666   __ ldr(lr, Address(r2, 0));       // Save return address
2667   __ enter();                       // and old rfp & set new rfp
2668   __ sub(sp, sp, r1);               // Prolog
2669   __ str(sender_sp, Address(rfp, frame::interpreter_frame_sender_sp_offset * wordSize)); // Make it walkable
2670   // This value is corrected by layout_activation_impl
2671   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
2672   __ mov(sender_sp, sp);          // Pass sender_sp to next frame
2673   __ add(r5, r5, wordSize);       // Bump array pointer (sizes)
2674   __ add(r2, r2, wordSize);       // Bump array pointer (pcs)
2675   __ subsw(r3, r3, 1);            // Decrement counter
2676   __ br(Assembler::GT, loop);
2677   __ ldr(lr, Address(r2, 0));     // save final return address
2678   // Re-push self-frame
2679   __ enter();                     // & old rfp & set new rfp
2680 
2681   // Use rfp because the frames look interpreted now
2682   // Save "the_pc" since it cannot easily be retrieved using the last_java_SP after we aligned SP.
2683   // Don't need the precise return PC here, just precise enough to point into this code blob.
2684   address the_pc = __ pc();
2685   __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
2686 
2687   // Call C code.  Need thread but NOT official VM entry
2688   // crud.  We cannot block on this call, no GC can happen.  Call should
2689   // restore return values to their stack-slots with the new SP.
2690   // Thread is in rdi already.
2691   //
2692   // BasicType unpack_frames(JavaThread* thread, int exec_mode);
2693   //
2694   // n.b. 2 gp args, 0 fp args, integral return type
2695 
2696   // sp should already be aligned
2697   __ mov(c_rarg0, rthread);
2698   __ movw(c_rarg1, (unsigned)Deoptimization::Unpack_uncommon_trap);
2699   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2700   __ blr(rscratch1);
2701 
2702   // Set an oopmap for the call site
2703   // Use the same PC we used for the last java frame
2704   oop_maps->add_gc_map(the_pc - start, new OopMap(SimpleRuntimeFrame::framesize, 0));
2705 
2706   // Clear fp AND pc
2707   __ reset_last_Java_frame(true);
2708 
2709   // Pop self-frame.
2710   __ leave();                 // Epilog
2711 
2712   // Jump to interpreter
2713   __ ret(lr);
2714 
2715   // Make sure all code is generated
2716   masm->flush();
2717 
2718   _uncommon_trap_blob =  UncommonTrapBlob::create(&buffer, oop_maps,
2719                                                  SimpleRuntimeFrame::framesize >> 1);
2720 }
2721 #endif // COMPILER2
2722 
2723 
2724 //------------------------------generate_handler_blob------
2725 //
2726 // Generate a special Compile2Runtime blob that saves all registers,
2727 // and setup oopmap.
2728 //
2729 SafepointBlob* SharedRuntime::generate_handler_blob(address call_ptr, int poll_type) {
2730   ResourceMark rm;
2731   OopMapSet *oop_maps = new OopMapSet();
2732   OopMap* map;
2733 
2734   // Allocate space for the code.  Setup code generation tools.
2735   CodeBuffer buffer("handler_blob", 2048, 1024);
2736   MacroAssembler* masm = new MacroAssembler(&buffer);
2737 
2738   address start   = __ pc();
2739   address call_pc = NULL;
2740   int frame_size_in_words;
2741   bool cause_return = (poll_type == POLL_AT_RETURN);
2742   RegisterSaver reg_save(poll_type == POLL_AT_VECTOR_LOOP /* save_vectors */);
2743 
2744   // Save Integer and Float registers.
2745   map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2746 
2747   // The following is basically a call_VM.  However, we need the precise
2748   // address of the call in order to generate an oopmap. Hence, we do all the
2749   // work outselves.
2750 
2751   Label retaddr;
2752   __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2753 
2754   // The return address must always be correct so that frame constructor never
2755   // sees an invalid pc.
2756 
2757   if (!cause_return) {
2758     // overwrite the return address pushed by save_live_registers
2759     // Additionally, r20 is a callee-saved register so we can look at
2760     // it later to determine if someone changed the return address for
2761     // us!
2762     __ ldr(r20, Address(rthread, JavaThread::saved_exception_pc_offset()));
2763     __ str(r20, Address(rfp, wordSize));
2764   }
2765 
2766   // Do the call
2767   __ mov(c_rarg0, rthread);
2768   __ lea(rscratch1, RuntimeAddress(call_ptr));
2769   __ blr(rscratch1);
2770   __ bind(retaddr);
2771 
2772   // Set an oopmap for the call site.  This oopmap will map all
2773   // oop-registers and debug-info registers as callee-saved.  This
2774   // will allow deoptimization at this safepoint to find all possible
2775   // debug-info recordings, as well as let GC find all oops.
2776 
2777   oop_maps->add_gc_map( __ pc() - start, map);
2778 
2779   Label noException;
2780 
2781   __ reset_last_Java_frame(false);
2782 
2783   __ membar(Assembler::LoadLoad | Assembler::LoadStore);
2784 
2785   __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
2786   __ cbz(rscratch1, noException);
2787 
2788   // Exception pending
2789 
2790   reg_save.restore_live_registers(masm);
2791 
2792   __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2793 
2794   // No exception case
2795   __ bind(noException);
2796 
2797   Label no_adjust, bail;
2798   if (!cause_return) {
2799     // If our stashed return pc was modified by the runtime we avoid touching it
2800     __ ldr(rscratch1, Address(rfp, wordSize));
2801     __ cmp(r20, rscratch1);
2802     __ br(Assembler::NE, no_adjust);
2803 
2804 #ifdef ASSERT
2805     // Verify the correct encoding of the poll we're about to skip.
2806     // See NativeInstruction::is_ldrw_to_zr()
2807     __ ldrw(rscratch1, Address(r20));
2808     __ ubfx(rscratch2, rscratch1, 22, 10);
2809     __ cmpw(rscratch2, 0b1011100101);
2810     __ br(Assembler::NE, bail);
2811     __ ubfx(rscratch2, rscratch1, 0, 5);
2812     __ cmpw(rscratch2, 0b11111);
2813     __ br(Assembler::NE, bail);
2814 #endif
2815     // Adjust return pc forward to step over the safepoint poll instruction
2816     __ add(r20, r20, NativeInstruction::instruction_size);
2817     __ str(r20, Address(rfp, wordSize));
2818   }
2819 
2820   __ bind(no_adjust);
2821   // Normal exit, restore registers and exit.
2822   reg_save.restore_live_registers(masm);
2823 
2824   __ ret(lr);
2825 
2826 #ifdef ASSERT
2827   __ bind(bail);
2828   __ stop("Attempting to adjust pc to skip safepoint poll but the return point is not what we expected");
2829 #endif
2830 
2831   // Make sure all code is generated
2832   masm->flush();
2833 
2834   // Fill-out other meta info
2835   return SafepointBlob::create(&buffer, oop_maps, frame_size_in_words);
2836 }
2837 
2838 //
2839 // generate_resolve_blob - call resolution (static/virtual/opt-virtual/ic-miss
2840 //
2841 // Generate a stub that calls into vm to find out the proper destination
2842 // of a java call. All the argument registers are live at this point
2843 // but since this is generic code we don't know what they are and the caller
2844 // must do any gc of the args.
2845 //
2846 RuntimeStub* SharedRuntime::generate_resolve_blob(address destination, const char* name) {
2847   assert (StubRoutines::forward_exception_entry() != NULL, "must be generated before");
2848 
2849   // allocate space for the code
2850   ResourceMark rm;
2851 
2852   CodeBuffer buffer(name, 1000, 512);
2853   MacroAssembler* masm                = new MacroAssembler(&buffer);
2854 
2855   int frame_size_in_words;
2856   RegisterSaver reg_save(false /* save_vectors */);
2857 
2858   OopMapSet *oop_maps = new OopMapSet();
2859   OopMap* map = NULL;
2860 
2861   int start = __ offset();
2862 
2863   map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2864 
2865   int frame_complete = __ offset();
2866 
2867   {
2868     Label retaddr;
2869     __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2870 
2871     __ mov(c_rarg0, rthread);
2872     __ lea(rscratch1, RuntimeAddress(destination));
2873 
2874     __ blr(rscratch1);
2875     __ bind(retaddr);
2876   }
2877 
2878   // Set an oopmap for the call site.
2879   // We need this not only for callee-saved registers, but also for volatile
2880   // registers that the compiler might be keeping live across a safepoint.
2881 
2882   oop_maps->add_gc_map( __ offset() - start, map);
2883 
2884   // r0 contains the address we are going to jump to assuming no exception got installed
2885 
2886   // clear last_Java_sp
2887   __ reset_last_Java_frame(false);
2888   // check for pending exceptions
2889   Label pending;
2890   __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
2891   __ cbnz(rscratch1, pending);
2892 
2893   // get the returned Method*
2894   __ get_vm_result_2(rmethod, rthread);
2895   __ str(rmethod, Address(sp, reg_save.reg_offset_in_bytes(rmethod)));
2896 
2897   // r0 is where we want to jump, overwrite rscratch1 which is saved and scratch
2898   __ str(r0, Address(sp, reg_save.rscratch1_offset_in_bytes()));
2899   reg_save.restore_live_registers(masm);
2900 
2901   // We are back the the original state on entry and ready to go.
2902 
2903   __ br(rscratch1);
2904 
2905   // Pending exception after the safepoint
2906 
2907   __ bind(pending);
2908 
2909   reg_save.restore_live_registers(masm);
2910 
2911   // exception pending => remove activation and forward to exception handler
2912 
2913   __ str(zr, Address(rthread, JavaThread::vm_result_offset()));
2914 
2915   __ ldr(r0, Address(rthread, Thread::pending_exception_offset()));
2916   __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2917 
2918   // -------------
2919   // make sure all code is generated
2920   masm->flush();
2921 
2922   // return the  blob
2923   // frame_size_words or bytes??
2924   return RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, frame_size_in_words, oop_maps, true);
2925 }
2926 
2927 #ifdef COMPILER2
2928 // This is here instead of runtime_x86_64.cpp because it uses SimpleRuntimeFrame
2929 //
2930 //------------------------------generate_exception_blob---------------------------
2931 // creates exception blob at the end
2932 // Using exception blob, this code is jumped from a compiled method.
2933 // (see emit_exception_handler in x86_64.ad file)
2934 //
2935 // Given an exception pc at a call we call into the runtime for the
2936 // handler in this method. This handler might merely restore state
2937 // (i.e. callee save registers) unwind the frame and jump to the
2938 // exception handler for the nmethod if there is no Java level handler
2939 // for the nmethod.
2940 //
2941 // This code is entered with a jmp.
2942 //
2943 // Arguments:
2944 //   r0: exception oop
2945 //   r3: exception pc
2946 //
2947 // Results:
2948 //   r0: exception oop
2949 //   r3: exception pc in caller or ???
2950 //   destination: exception handler of caller
2951 //
2952 // Note: the exception pc MUST be at a call (precise debug information)
2953 //       Registers r0, r3, r2, r4, r5, r8-r11 are not callee saved.
2954 //
2955 
2956 void OptoRuntime::generate_exception_blob() {
2957   assert(!OptoRuntime::is_callee_saved_register(R3_num), "");
2958   assert(!OptoRuntime::is_callee_saved_register(R0_num), "");
2959   assert(!OptoRuntime::is_callee_saved_register(R2_num), "");
2960 
2961   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
2962 
2963   // Allocate space for the code
2964   ResourceMark rm;
2965   // Setup code generation tools
2966   CodeBuffer buffer("exception_blob", 2048, 1024);
2967   MacroAssembler* masm = new MacroAssembler(&buffer);
2968 
2969   // TODO check various assumptions made here
2970   //
2971   // make sure we do so before running this
2972 
2973   address start = __ pc();
2974 
2975   // push rfp and retaddr by hand
2976   // Exception pc is 'return address' for stack walker
2977   __ stp(rfp, lr, Address(__ pre(sp, -2 * wordSize)));
2978   // there are no callee save registers and we don't expect an
2979   // arg reg save area
2980 #ifndef PRODUCT
2981   assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
2982 #endif
2983   // Store exception in Thread object. We cannot pass any arguments to the
2984   // handle_exception call, since we do not want to make any assumption
2985   // about the size of the frame where the exception happened in.
2986   __ str(r0, Address(rthread, JavaThread::exception_oop_offset()));
2987   __ str(r3, Address(rthread, JavaThread::exception_pc_offset()));
2988 
2989   // This call does all the hard work.  It checks if an exception handler
2990   // exists in the method.
2991   // If so, it returns the handler address.
2992   // If not, it prepares for stack-unwinding, restoring the callee-save
2993   // registers of the frame being removed.
2994   //
2995   // address OptoRuntime::handle_exception_C(JavaThread* thread)
2996   //
2997   // n.b. 1 gp arg, 0 fp args, integral return type
2998 
2999   // the stack should always be aligned
3000   address the_pc = __ pc();
3001   __ set_last_Java_frame(sp, noreg, the_pc, rscratch1);
3002   __ mov(c_rarg0, rthread);
3003   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, OptoRuntime::handle_exception_C)));
3004   __ blr(rscratch1);
3005   // handle_exception_C is a special VM call which does not require an explicit
3006   // instruction sync afterwards.
3007 
3008   // May jump to SVE compiled code
3009   __ reinitialize_ptrue();
3010 
3011   // Set an oopmap for the call site.  This oopmap will only be used if we
3012   // are unwinding the stack.  Hence, all locations will be dead.
3013   // Callee-saved registers will be the same as the frame above (i.e.,
3014   // handle_exception_stub), since they were restored when we got the
3015   // exception.
3016 
3017   OopMapSet* oop_maps = new OopMapSet();
3018 
3019   oop_maps->add_gc_map(the_pc - start, new OopMap(SimpleRuntimeFrame::framesize, 0));
3020 
3021   __ reset_last_Java_frame(false);
3022 
3023   // Restore callee-saved registers
3024 
3025   // rfp is an implicitly saved callee saved register (i.e. the calling
3026   // convention will save restore it in prolog/epilog) Other than that
3027   // there are no callee save registers now that adapter frames are gone.
3028   // and we dont' expect an arg reg save area
3029   __ ldp(rfp, r3, Address(__ post(sp, 2 * wordSize)));
3030 
3031   // r0: exception handler
3032 
3033   // We have a handler in r0 (could be deopt blob).
3034   __ mov(r8, r0);
3035 
3036   // Get the exception oop
3037   __ ldr(r0, Address(rthread, JavaThread::exception_oop_offset()));
3038   // Get the exception pc in case we are deoptimized
3039   __ ldr(r4, Address(rthread, JavaThread::exception_pc_offset()));
3040 #ifdef ASSERT
3041   __ str(zr, Address(rthread, JavaThread::exception_handler_pc_offset()));
3042   __ str(zr, Address(rthread, JavaThread::exception_pc_offset()));
3043 #endif
3044   // Clear the exception oop so GC no longer processes it as a root.
3045   __ str(zr, Address(rthread, JavaThread::exception_oop_offset()));
3046 
3047   // r0: exception oop
3048   // r8:  exception handler
3049   // r4: exception pc
3050   // Jump to handler
3051 
3052   __ br(r8);
3053 
3054   // Make sure all code is generated
3055   masm->flush();
3056 
3057   // Set exception blob
3058   _exception_blob =  ExceptionBlob::create(&buffer, oop_maps, SimpleRuntimeFrame::framesize >> 1);
3059 }
3060 
3061 // ---------------------------------------------------------------
3062 
3063 class NativeInvokerGenerator : public StubCodeGenerator {
3064   address _call_target;
3065   int _shadow_space_bytes;
3066 
3067   const GrowableArray<VMReg>& _input_registers;
3068   const GrowableArray<VMReg>& _output_registers;
3069 
3070   int _frame_complete;
3071   int _framesize;
3072   OopMapSet* _oop_maps;
3073 public:
3074   NativeInvokerGenerator(CodeBuffer* buffer,
3075                          address call_target,
3076                          int shadow_space_bytes,
3077                          const GrowableArray<VMReg>& input_registers,
3078                          const GrowableArray<VMReg>& output_registers)
3079    : StubCodeGenerator(buffer, PrintMethodHandleStubs),
3080      _call_target(call_target),
3081      _shadow_space_bytes(shadow_space_bytes),
3082      _input_registers(input_registers),
3083      _output_registers(output_registers),
3084      _frame_complete(0),
3085      _framesize(0),
3086      _oop_maps(NULL) {
3087     assert(_output_registers.length() <= 1
3088            || (_output_registers.length() == 2 && !_output_registers.at(1)->is_valid()), "no multi-reg returns");
3089   }
3090 
3091   void generate();
3092 
3093   int spill_size_in_bytes() const {
3094     if (_output_registers.length() == 0) {
3095       return 0;
3096     }
3097     VMReg reg = _output_registers.at(0);
3098     assert(reg->is_reg(), "must be a register");
3099     if (reg->is_Register()) {
3100       return 8;
3101     } else if (reg->is_FloatRegister()) {
3102       bool use_sve = Matcher::supports_scalable_vector();
3103       if (use_sve) {
3104         return Matcher::scalable_vector_reg_size(T_BYTE);
3105       }
3106       return 16;
3107     } else {
3108       ShouldNotReachHere();
3109     }
3110     return 0;
3111   }
3112 
3113   void spill_output_registers() {
3114     if (_output_registers.length() == 0) {
3115       return;
3116     }
3117     VMReg reg = _output_registers.at(0);
3118     assert(reg->is_reg(), "must be a register");
3119     MacroAssembler* masm = _masm;
3120     if (reg->is_Register()) {
3121       __ spill(reg->as_Register(), true, 0);
3122     } else if (reg->is_FloatRegister()) {
3123       bool use_sve = Matcher::supports_scalable_vector();
3124       if (use_sve) {
3125         __ spill_sve_vector(reg->as_FloatRegister(), 0, Matcher::scalable_vector_reg_size(T_BYTE));
3126       } else {
3127         __ spill(reg->as_FloatRegister(), __ Q, 0);
3128       }
3129     } else {
3130       ShouldNotReachHere();
3131     }
3132   }
3133 
3134   void fill_output_registers() {
3135     if (_output_registers.length() == 0) {
3136       return;
3137     }
3138     VMReg reg = _output_registers.at(0);
3139     assert(reg->is_reg(), "must be a register");
3140     MacroAssembler* masm = _masm;
3141     if (reg->is_Register()) {
3142       __ unspill(reg->as_Register(), true, 0);
3143     } else if (reg->is_FloatRegister()) {
3144       bool use_sve = Matcher::supports_scalable_vector();
3145       if (use_sve) {
3146         __ unspill_sve_vector(reg->as_FloatRegister(), 0, Matcher::scalable_vector_reg_size(T_BYTE));
3147       } else {
3148         __ unspill(reg->as_FloatRegister(), __ Q, 0);
3149       }
3150     } else {
3151       ShouldNotReachHere();
3152     }
3153   }
3154 
3155   int frame_complete() const {
3156     return _frame_complete;
3157   }
3158 
3159   int framesize() const {
3160     return (_framesize >> (LogBytesPerWord - LogBytesPerInt));
3161   }
3162 
3163   OopMapSet* oop_maps() const {
3164     return _oop_maps;
3165   }
3166 
3167 private:
3168 #ifdef ASSERT
3169   bool target_uses_register(VMReg reg) {
3170     return _input_registers.contains(reg) || _output_registers.contains(reg);
3171   }
3172 #endif
3173 };
3174 
3175 static const int native_invoker_code_size = 1024;
3176 
3177 RuntimeStub* SharedRuntime::make_native_invoker(address call_target,
3178                                                 int shadow_space_bytes,
3179                                                 const GrowableArray<VMReg>& input_registers,
3180                                                 const GrowableArray<VMReg>& output_registers) {
3181   int locs_size  = 64;
3182   CodeBuffer code("nep_invoker_blob", native_invoker_code_size, locs_size);
3183   NativeInvokerGenerator g(&code, call_target, shadow_space_bytes, input_registers, output_registers);
3184   g.generate();
3185   code.log_section_sizes("nep_invoker_blob");
3186 
3187   RuntimeStub* stub =
3188     RuntimeStub::new_runtime_stub("nep_invoker_blob",
3189                                   &code,
3190                                   g.frame_complete(),
3191                                   g.framesize(),
3192                                   g.oop_maps(), false);
3193   return stub;
3194 }
3195 
3196 void NativeInvokerGenerator::generate() {
3197   assert(!(target_uses_register(rscratch1->as_VMReg())
3198            || target_uses_register(rscratch2->as_VMReg())
3199            || target_uses_register(rthread->as_VMReg())),
3200          "Register conflict");
3201 
3202   enum layout {
3203     rbp_off,
3204     rbp_off2,
3205     return_off,
3206     return_off2,
3207     framesize // inclusive of return address
3208   };
3209 
3210   assert(_shadow_space_bytes == 0, "not expecting shadow space on AArch64");
3211   _framesize = align_up(framesize + (spill_size_in_bytes() >> LogBytesPerInt), 4);
3212   assert(is_even(_framesize/2), "sp not 16-byte aligned");
3213 
3214   _oop_maps  = new OopMapSet();
3215   MacroAssembler* masm = _masm;
3216 
3217   address start = __ pc();
3218 
3219   __ enter();
3220 
3221   // lr and fp are already in place
3222   __ sub(sp, rfp, ((unsigned)_framesize-4) << LogBytesPerInt); // prolog
3223 
3224   _frame_complete = __ pc() - start;
3225 
3226   address the_pc = __ pc();
3227   __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
3228   OopMap* map = new OopMap(_framesize, 0);
3229   _oop_maps->add_gc_map(the_pc - start, map);
3230 
3231   // State transition
3232   __ mov(rscratch1, _thread_in_native);
3233   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
3234   __ stlrw(rscratch1, rscratch2);
3235 
3236   rt_call(masm, _call_target);
3237 
3238   __ mov(rscratch1, _thread_in_native_trans);
3239   __ strw(rscratch1, Address(rthread, JavaThread::thread_state_offset()));
3240 
3241   // Force this write out before the read below
3242   __ membar(Assembler::LoadLoad | Assembler::LoadStore |
3243             Assembler::StoreLoad | Assembler::StoreStore);
3244 
3245   __ verify_sve_vector_length();
3246 
3247   Label L_after_safepoint_poll;
3248   Label L_safepoint_poll_slow_path;
3249 
3250   __ safepoint_poll(L_safepoint_poll_slow_path, true /* at_return */, true /* acquire */, false /* in_nmethod */);
3251 
3252   __ ldrw(rscratch1, Address(rthread, JavaThread::suspend_flags_offset()));
3253   __ cbnzw(rscratch1, L_safepoint_poll_slow_path);
3254 
3255   __ bind(L_after_safepoint_poll);
3256 
3257   // change thread state
3258   __ mov(rscratch1, _thread_in_Java);
3259   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
3260   __ stlrw(rscratch1, rscratch2);
3261 
3262   __ block_comment("reguard stack check");
3263   Label L_reguard;
3264   Label L_after_reguard;
3265   __ ldrb(rscratch1, Address(rthread, JavaThread::stack_guard_state_offset()));
3266   __ cmpw(rscratch1, StackOverflow::stack_guard_yellow_reserved_disabled);
3267   __ br(Assembler::EQ, L_reguard);
3268   __ bind(L_after_reguard);
3269 
3270   __ reset_last_Java_frame(true);
3271 
3272   __ leave(); // required for proper stackwalking of RuntimeStub frame
3273   __ ret(lr);
3274 
3275   //////////////////////////////////////////////////////////////////////////////
3276 
3277   __ block_comment("{ L_safepoint_poll_slow_path");
3278   __ bind(L_safepoint_poll_slow_path);
3279 
3280   // Need to save the native result registers around any runtime calls.
3281   spill_output_registers();
3282 
3283   __ mov(c_rarg0, rthread);
3284   assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
3285   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans)));
3286   __ blr(rscratch1);
3287 
3288   fill_output_registers();
3289 
3290   __ b(L_after_safepoint_poll);
3291   __ block_comment("} L_safepoint_poll_slow_path");
3292 
3293   //////////////////////////////////////////////////////////////////////////////
3294 
3295   __ block_comment("{ L_reguard");
3296   __ bind(L_reguard);
3297 
3298   spill_output_registers();
3299 
3300   rt_call(masm, CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages));
3301 
3302   fill_output_registers();
3303 
3304   __ b(L_after_reguard);
3305 
3306   __ block_comment("} L_reguard");
3307 
3308   //////////////////////////////////////////////////////////////////////////////
3309 
3310   __ flush();
3311 }
3312 #endif // COMPILER2
--- EOF ---