1 /*
   2  * Copyright (c) 2003, 2025, 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 "asm/macroAssembler.hpp"
  28 #include "asm/macroAssembler.inline.hpp"
  29 #include "classfile/symbolTable.hpp"
  30 #include "code/aotCodeCache.hpp"
  31 #include "code/codeCache.hpp"
  32 #include "code/compiledIC.hpp"
  33 #include "code/debugInfoRec.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/klass.inline.hpp"
  43 #include "oops/method.inline.hpp"
  44 #include "prims/methodHandles.hpp"
  45 #include "runtime/continuation.hpp"
  46 #include "runtime/continuationEntry.inline.hpp"
  47 #include "runtime/globals.hpp"
  48 #include "runtime/jniHandles.hpp"
  49 #include "runtime/safepointMechanism.hpp"
  50 #include "runtime/sharedRuntime.hpp"
  51 #include "runtime/signature.hpp"
  52 #include "runtime/stubRoutines.hpp"
  53 #include "runtime/timerTrace.hpp"
  54 #include "runtime/vframeArray.hpp"
  55 #include "utilities/align.hpp"
  56 #include "utilities/formatBuffer.hpp"
  57 #include "vmreg_aarch64.inline.hpp"
  58 #ifdef COMPILER1
  59 #include "c1/c1_Runtime1.hpp"
  60 #endif
  61 #ifdef COMPILER2
  62 #include "adfiles/ad_aarch64.hpp"
  63 #include "opto/runtime.hpp"
  64 #endif
  65 #if INCLUDE_JVMCI
  66 #include "jvmci/jvmciJavaClasses.hpp"
  67 #endif
  68 
  69 #define __ masm->
  70 
  71 #ifdef PRODUCT
  72 #define BLOCK_COMMENT(str) /* nothing */
  73 #else
  74 #define BLOCK_COMMENT(str) __ block_comment(str)
  75 #endif
  76 
  77 const int StackAlignmentInSlots = StackAlignmentInBytes / VMRegImpl::stack_slot_size;
  78 
  79 // FIXME -- this is used by C1
  80 class RegisterSaver {
  81   const bool _save_vectors;
  82  public:
  83   RegisterSaver(bool save_vectors) : _save_vectors(save_vectors) {}
  84 
  85   OopMap* save_live_registers(MacroAssembler* masm, int additional_frame_words, int* total_frame_words);
  86   void restore_live_registers(MacroAssembler* masm);
  87 
  88   // Offsets into the register save area
  89   // Used by deoptimization when it is managing result register
  90   // values on its own
  91 
  92   int reg_offset_in_bytes(Register r);
  93   int r0_offset_in_bytes()    { return reg_offset_in_bytes(r0); }
  94   int rscratch1_offset_in_bytes()    { return reg_offset_in_bytes(rscratch1); }
  95   int v0_offset_in_bytes();
  96 
  97   // Total stack size in bytes for saving sve predicate registers.
  98   int total_sve_predicate_in_bytes();
  99 
 100   // Capture info about frame layout
 101   // Note this is only correct when not saving full vectors.
 102   enum layout {
 103                 fpu_state_off = 0,
 104                 fpu_state_end = fpu_state_off + FPUStateSizeInWords - 1,
 105                 // The frame sender code expects that rfp will be in
 106                 // the "natural" place and will override any oopMap
 107                 // setting for it. We must therefore force the layout
 108                 // so that it agrees with the frame sender code.
 109                 r0_off = fpu_state_off + FPUStateSizeInWords,
 110                 rfp_off = r0_off + (Register::number_of_registers - 2) * Register::max_slots_per_register,
 111                 return_off = rfp_off + Register::max_slots_per_register,      // slot for return address
 112                 reg_save_size = return_off + Register::max_slots_per_register};
 113 
 114 };
 115 
 116 int RegisterSaver::reg_offset_in_bytes(Register r) {
 117   // The integer registers are located above the floating point
 118   // registers in the stack frame pushed by save_live_registers() so the
 119   // offset depends on whether we are saving full vectors, and whether
 120   // those vectors are NEON or SVE.
 121 
 122   int slots_per_vect = FloatRegister::save_slots_per_register;
 123 
 124 #if COMPILER2_OR_JVMCI
 125   if (_save_vectors) {
 126     slots_per_vect = FloatRegister::slots_per_neon_register;
 127 
 128 #ifdef COMPILER2
 129     if (Matcher::supports_scalable_vector()) {
 130       slots_per_vect = Matcher::scalable_vector_reg_size(T_FLOAT);
 131     }
 132 #endif
 133   }
 134 #endif
 135 
 136   int r0_offset = v0_offset_in_bytes() + (slots_per_vect * FloatRegister::number_of_registers) * BytesPerInt;
 137   return r0_offset + r->encoding() * wordSize;
 138 }
 139 
 140 int RegisterSaver::v0_offset_in_bytes() {
 141   // The floating point registers are located above the predicate registers if
 142   // they are present in the stack frame pushed by save_live_registers(). So the
 143   // offset depends on the saved total predicate vectors in the stack frame.
 144   return (total_sve_predicate_in_bytes() / VMRegImpl::stack_slot_size) * BytesPerInt;
 145 }
 146 
 147 int RegisterSaver::total_sve_predicate_in_bytes() {
 148 #ifdef COMPILER2
 149   if (_save_vectors && Matcher::supports_scalable_vector()) {
 150     return (Matcher::scalable_vector_reg_size(T_BYTE) >> LogBitsPerByte) *
 151            PRegister::number_of_registers;
 152   }
 153 #endif
 154   return 0;
 155 }
 156 
 157 OopMap* RegisterSaver::save_live_registers(MacroAssembler* masm, int additional_frame_words, int* total_frame_words) {
 158   bool use_sve = false;
 159   int sve_vector_size_in_bytes = 0;
 160   int sve_vector_size_in_slots = 0;
 161   int sve_predicate_size_in_slots = 0;
 162   int total_predicate_in_bytes = total_sve_predicate_in_bytes();
 163   int total_predicate_in_slots = total_predicate_in_bytes / VMRegImpl::stack_slot_size;
 164 
 165 #ifdef COMPILER2
 166   use_sve = Matcher::supports_scalable_vector();
 167   if (use_sve) {
 168     sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
 169     sve_vector_size_in_slots = Matcher::scalable_vector_reg_size(T_FLOAT);
 170     sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
 171   }
 172 #endif
 173 
 174 #if COMPILER2_OR_JVMCI
 175   if (_save_vectors) {
 176     int extra_save_slots_per_register = 0;
 177     // Save upper half of vector registers
 178     if (use_sve) {
 179       extra_save_slots_per_register = sve_vector_size_in_slots - FloatRegister::save_slots_per_register;
 180     } else {
 181       extra_save_slots_per_register = FloatRegister::extra_save_slots_per_neon_register;
 182     }
 183     int extra_vector_bytes = extra_save_slots_per_register *
 184                              VMRegImpl::stack_slot_size *
 185                              FloatRegister::number_of_registers;
 186     additional_frame_words += ((extra_vector_bytes + total_predicate_in_bytes) / wordSize);
 187   }
 188 #else
 189   assert(!_save_vectors, "vectors are generated only by C2 and JVMCI");
 190 #endif
 191 
 192   int frame_size_in_bytes = align_up(additional_frame_words * wordSize +
 193                                      reg_save_size * BytesPerInt, 16);
 194   // OopMap frame size is in compiler stack slots (jint's) not bytes or words
 195   int frame_size_in_slots = frame_size_in_bytes / BytesPerInt;
 196   // The caller will allocate additional_frame_words
 197   int additional_frame_slots = additional_frame_words * wordSize / BytesPerInt;
 198   // CodeBlob frame size is in words.
 199   int frame_size_in_words = frame_size_in_bytes / wordSize;
 200   *total_frame_words = frame_size_in_words;
 201 
 202   // Save Integer and Float registers.
 203   __ enter();
 204   __ push_CPU_state(_save_vectors, use_sve, sve_vector_size_in_bytes, total_predicate_in_bytes);
 205 
 206   // Set an oopmap for the call site.  This oopmap will map all
 207   // oop-registers and debug-info registers as callee-saved.  This
 208   // will allow deoptimization at this safepoint to find all possible
 209   // debug-info recordings, as well as let GC find all oops.
 210 
 211   OopMapSet *oop_maps = new OopMapSet();
 212   OopMap* oop_map = new OopMap(frame_size_in_slots, 0);
 213 
 214   for (int i = 0; i < Register::number_of_registers; i++) {
 215     Register r = as_Register(i);
 216     if (i <= rfp->encoding() && r != rscratch1 && r != rscratch2) {
 217       // SP offsets are in 4-byte words.
 218       // Register slots are 8 bytes wide, 32 floating-point registers.
 219       int sp_offset = Register::max_slots_per_register * i +
 220                       FloatRegister::save_slots_per_register * FloatRegister::number_of_registers;
 221       oop_map->set_callee_saved(VMRegImpl::stack2reg(sp_offset + additional_frame_slots), r->as_VMReg());
 222     }
 223   }
 224 
 225   for (int i = 0; i < FloatRegister::number_of_registers; i++) {
 226     FloatRegister r = as_FloatRegister(i);
 227     int sp_offset = 0;
 228     if (_save_vectors) {
 229       sp_offset = use_sve ? (total_predicate_in_slots + sve_vector_size_in_slots * i) :
 230                             (FloatRegister::slots_per_neon_register * i);
 231     } else {
 232       sp_offset = FloatRegister::save_slots_per_register * i;
 233     }
 234     oop_map->set_callee_saved(VMRegImpl::stack2reg(sp_offset), r->as_VMReg());
 235   }
 236 
 237   return oop_map;
 238 }
 239 
 240 void RegisterSaver::restore_live_registers(MacroAssembler* masm) {
 241 #ifdef COMPILER2
 242   __ pop_CPU_state(_save_vectors, Matcher::supports_scalable_vector(),
 243                    Matcher::scalable_vector_reg_size(T_BYTE), total_sve_predicate_in_bytes());
 244 #else
 245 #if !INCLUDE_JVMCI
 246   assert(!_save_vectors, "vectors are generated only by C2 and JVMCI");
 247 #endif
 248   __ pop_CPU_state(_save_vectors);
 249 #endif
 250   __ ldp(rfp, lr, Address(__ post(sp, 2 * wordSize)));
 251   __ authenticate_return_address();
 252 }
 253 
 254 // Is vector's size (in bytes) bigger than a size saved by default?
 255 // 8 bytes vector registers are saved by default on AArch64.
 256 // The SVE supported min vector size is 8 bytes and we need to save
 257 // predicate registers when the vector size is 8 bytes as well.
 258 bool SharedRuntime::is_wide_vector(int size) {
 259   return size > 8 || (UseSVE > 0 && size >= 8);
 260 }
 261 
 262 // ---------------------------------------------------------------------------
 263 // Read the array of BasicTypes from a signature, and compute where the
 264 // arguments should go.  Values in the VMRegPair regs array refer to 4-byte
 265 // quantities.  Values less than VMRegImpl::stack0 are registers, those above
 266 // refer to 4-byte stack slots.  All stack slots are based off of the stack pointer
 267 // as framesizes are fixed.
 268 // VMRegImpl::stack0 refers to the first slot 0(sp).
 269 // and VMRegImpl::stack0+1 refers to the memory word 4-byes higher.
 270 // Register up to Register::number_of_registers are the 64-bit
 271 // integer registers.
 272 
 273 // Note: the INPUTS in sig_bt are in units of Java argument words,
 274 // which are 64-bit.  The OUTPUTS are in 32-bit units.
 275 
 276 // The Java calling convention is a "shifted" version of the C ABI.
 277 // By skipping the first C ABI register we can call non-static jni
 278 // methods with small numbers of arguments without having to shuffle
 279 // the arguments at all. Since we control the java ABI we ought to at
 280 // least get some advantage out of it.
 281 
 282 int SharedRuntime::java_calling_convention(const BasicType *sig_bt,
 283                                            VMRegPair *regs,
 284                                            int total_args_passed) {
 285 
 286   // Create the mapping between argument positions and
 287   // registers.
 288   static const Register INT_ArgReg[Argument::n_int_register_parameters_j] = {
 289     j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5, j_rarg6, j_rarg7
 290   };
 291   static const FloatRegister FP_ArgReg[Argument::n_float_register_parameters_j] = {
 292     j_farg0, j_farg1, j_farg2, j_farg3,
 293     j_farg4, j_farg5, j_farg6, j_farg7
 294   };
 295 
 296 
 297   uint int_args = 0;
 298   uint fp_args = 0;
 299   uint stk_args = 0;
 300 
 301   for (int i = 0; i < total_args_passed; i++) {
 302     switch (sig_bt[i]) {
 303     case T_BOOLEAN:
 304     case T_CHAR:
 305     case T_BYTE:
 306     case T_SHORT:
 307     case T_INT:
 308       if (int_args < Argument::n_int_register_parameters_j) {
 309         regs[i].set1(INT_ArgReg[int_args++]->as_VMReg());
 310       } else {
 311         stk_args = align_up(stk_args, 2);
 312         regs[i].set1(VMRegImpl::stack2reg(stk_args));
 313         stk_args += 1;
 314       }
 315       break;
 316     case T_VOID:
 317       // halves of T_LONG or T_DOUBLE
 318       assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
 319       regs[i].set_bad();
 320       break;
 321     case T_LONG:
 322       assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
 323       // fall through
 324     case T_OBJECT:
 325     case T_ARRAY:
 326     case T_ADDRESS:
 327       if (int_args < Argument::n_int_register_parameters_j) {
 328         regs[i].set2(INT_ArgReg[int_args++]->as_VMReg());
 329       } else {
 330         stk_args = align_up(stk_args, 2);
 331         regs[i].set2(VMRegImpl::stack2reg(stk_args));
 332         stk_args += 2;
 333       }
 334       break;
 335     case T_FLOAT:
 336       if (fp_args < Argument::n_float_register_parameters_j) {
 337         regs[i].set1(FP_ArgReg[fp_args++]->as_VMReg());
 338       } else {
 339         stk_args = align_up(stk_args, 2);
 340         regs[i].set1(VMRegImpl::stack2reg(stk_args));
 341         stk_args += 1;
 342       }
 343       break;
 344     case T_DOUBLE:
 345       assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
 346       if (fp_args < Argument::n_float_register_parameters_j) {
 347         regs[i].set2(FP_ArgReg[fp_args++]->as_VMReg());
 348       } else {
 349         stk_args = align_up(stk_args, 2);
 350         regs[i].set2(VMRegImpl::stack2reg(stk_args));
 351         stk_args += 2;
 352       }
 353       break;
 354     default:
 355       ShouldNotReachHere();
 356       break;
 357     }
 358   }
 359 
 360   return stk_args;
 361 }
 362 
 363 
 364 const uint SharedRuntime::java_return_convention_max_int = Argument::n_int_register_parameters_j;
 365 const uint SharedRuntime::java_return_convention_max_float = Argument::n_float_register_parameters_j;
 366 
 367 int SharedRuntime::java_return_convention(const BasicType *sig_bt, VMRegPair *regs, int total_args_passed) {
 368 
 369   // Create the mapping between argument positions and registers.
 370 
 371   static const Register INT_ArgReg[java_return_convention_max_int] = {
 372     r0 /* j_rarg7 */, j_rarg6, j_rarg5, j_rarg4, j_rarg3, j_rarg2, j_rarg1, j_rarg0
 373   };
 374 
 375   static const FloatRegister FP_ArgReg[java_return_convention_max_float] = {
 376     j_farg0, j_farg1, j_farg2, j_farg3, j_farg4, j_farg5, j_farg6, j_farg7
 377   };
 378 
 379   uint int_args = 0;
 380   uint fp_args = 0;
 381 
 382   for (int i = 0; i < total_args_passed; i++) {
 383     switch (sig_bt[i]) {
 384     case T_BOOLEAN:
 385     case T_CHAR:
 386     case T_BYTE:
 387     case T_SHORT:
 388     case T_INT:
 389       if (int_args < SharedRuntime::java_return_convention_max_int) {
 390         regs[i].set1(INT_ArgReg[int_args]->as_VMReg());
 391         int_args ++;
 392       } else {
 393         return -1;
 394       }
 395       break;
 396     case T_VOID:
 397       // halves of T_LONG or T_DOUBLE
 398       assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
 399       regs[i].set_bad();
 400       break;
 401     case T_LONG:
 402       assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
 403       // fall through
 404     case T_OBJECT:
 405     case T_ARRAY:
 406     case T_ADDRESS:
 407       // Should T_METADATA be added to java_calling_convention as well ?
 408     case T_METADATA:
 409       if (int_args < SharedRuntime::java_return_convention_max_int) {
 410         regs[i].set2(INT_ArgReg[int_args]->as_VMReg());
 411         int_args ++;
 412       } else {
 413         return -1;
 414       }
 415       break;
 416     case T_FLOAT:
 417       if (fp_args < SharedRuntime::java_return_convention_max_float) {
 418         regs[i].set1(FP_ArgReg[fp_args]->as_VMReg());
 419         fp_args ++;
 420       } else {
 421         return -1;
 422       }
 423       break;
 424     case T_DOUBLE:
 425       assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
 426       if (fp_args < SharedRuntime::java_return_convention_max_float) {
 427         regs[i].set2(FP_ArgReg[fp_args]->as_VMReg());
 428         fp_args ++;
 429       } else {
 430         return -1;
 431       }
 432       break;
 433     default:
 434       ShouldNotReachHere();
 435       break;
 436     }
 437   }
 438 
 439   return int_args + fp_args;
 440 }
 441 
 442 // Patch the callers callsite with entry to compiled code if it exists.
 443 static void patch_callers_callsite(MacroAssembler *masm) {
 444   Label L;
 445   __ ldr(rscratch1, Address(rmethod, in_bytes(Method::code_offset())));
 446   __ cbz(rscratch1, L);
 447 
 448   __ enter();
 449   __ push_CPU_state();
 450 
 451   // VM needs caller's callsite
 452   // VM needs target method
 453   // This needs to be a long call since we will relocate this adapter to
 454   // the codeBuffer and it may not reach
 455 
 456 #ifndef PRODUCT
 457   assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
 458 #endif
 459 
 460   __ mov(c_rarg0, rmethod);
 461   __ mov(c_rarg1, lr);
 462   __ authenticate_return_address(c_rarg1);
 463   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::fixup_callers_callsite)));
 464   __ blr(rscratch1);
 465 
 466   // Explicit isb required because fixup_callers_callsite may change the code
 467   // stream.
 468   __ safepoint_isb();
 469 
 470   __ pop_CPU_state();
 471   // restore sp
 472   __ leave();
 473   __ bind(L);
 474 }
 475 
 476 // For each inline type argument, sig includes the list of fields of
 477 // the inline type. This utility function computes the number of
 478 // arguments for the call if inline types are passed by reference (the
 479 // calling convention the interpreter expects).
 480 static int compute_total_args_passed_int(const GrowableArray<SigEntry>* sig_extended) {
 481   int total_args_passed = 0;
 482   if (InlineTypePassFieldsAsArgs) {
 483     for (int i = 0; i < sig_extended->length(); i++) {
 484       BasicType bt = sig_extended->at(i)._bt;
 485       if (bt == T_METADATA) {
 486         // In sig_extended, an inline type argument starts with:
 487         // T_METADATA, followed by the types of the fields of the
 488         // inline type and T_VOID to mark the end of the value
 489         // type. Inline types are flattened so, for instance, in the
 490         // case of an inline type with an int field and an inline type
 491         // field that itself has 2 fields, an int and a long:
 492         // T_METADATA T_INT T_METADATA T_INT T_LONG T_VOID (second
 493         // slot for the T_LONG) T_VOID (inner inline type) T_VOID
 494         // (outer inline type)
 495         total_args_passed++;
 496         int vt = 1;
 497         do {
 498           i++;
 499           BasicType bt = sig_extended->at(i)._bt;
 500           BasicType prev_bt = sig_extended->at(i-1)._bt;
 501           if (bt == T_METADATA) {
 502             vt++;
 503           } else if (bt == T_VOID &&
 504                      prev_bt != T_LONG &&
 505                      prev_bt != T_DOUBLE) {
 506             vt--;
 507           }
 508         } while (vt != 0);
 509       } else {
 510         total_args_passed++;
 511       }
 512     }
 513   } else {
 514     total_args_passed = sig_extended->length();
 515   }
 516   return total_args_passed;
 517 }
 518 
 519 
 520 static void gen_c2i_adapter_helper(MacroAssembler* masm,
 521                                    BasicType bt,
 522                                    BasicType prev_bt,
 523                                    size_t size_in_bytes,
 524                                    const VMRegPair& reg_pair,
 525                                    const Address& to,
 526                                    Register tmp1,
 527                                    Register tmp2,
 528                                    Register tmp3,
 529                                    int extraspace,
 530                                    bool is_oop) {
 531   if (bt == T_VOID) {
 532     assert(prev_bt == T_LONG || prev_bt == T_DOUBLE, "missing half");
 533     return;
 534   }
 535 
 536   // Say 4 args:
 537   // i   st_off
 538   // 0   32 T_LONG
 539   // 1   24 T_VOID
 540   // 2   16 T_OBJECT
 541   // 3    8 T_BOOL
 542   // -    0 return address
 543   //
 544   // However to make thing extra confusing. Because we can fit a Java long/double in
 545   // a single slot on a 64 bt vm and it would be silly to break them up, the interpreter
 546   // leaves one slot empty and only stores to a single slot. In this case the
 547   // slot that is occupied is the T_VOID slot. See I said it was confusing.
 548 
 549   bool wide = (size_in_bytes == wordSize);
 550   VMReg r_1 = reg_pair.first();
 551   VMReg r_2 = reg_pair.second();
 552   assert(r_2->is_valid() == wide, "invalid size");
 553   if (!r_1->is_valid()) {
 554     assert(!r_2->is_valid(), "");
 555     return;
 556   }
 557 
 558   if (!r_1->is_FloatRegister()) {
 559     Register val = r25;
 560     if (r_1->is_stack()) {
 561       // memory to memory use r25 (scratch registers is used by store_heap_oop)
 562       int ld_off = r_1->reg2stack() * VMRegImpl::stack_slot_size + extraspace;
 563       __ load_sized_value(val, Address(sp, ld_off), size_in_bytes, /* is_signed */ false);
 564     } else {
 565       val = r_1->as_Register();
 566     }
 567     assert_different_registers(to.base(), val, tmp1, tmp2, tmp3);
 568     if (is_oop) {
 569       __ store_heap_oop(to, val, tmp1, tmp2, tmp3, IN_HEAP | ACCESS_WRITE | IS_DEST_UNINITIALIZED);
 570     } else {
 571       __ store_sized_value(to, val, size_in_bytes);
 572     }
 573   } else {
 574     if (wide) {
 575       __ strd(r_1->as_FloatRegister(), to);
 576     } else {
 577       // only a float use just part of the slot
 578       __ strs(r_1->as_FloatRegister(), to);
 579     }
 580   }
 581 }
 582 
 583 static void gen_c2i_adapter(MacroAssembler *masm,
 584                             const GrowableArray<SigEntry>* sig_extended,


 585                             const VMRegPair *regs,
 586                             bool requires_clinit_barrier,
 587                             address& c2i_no_clinit_check_entry,
 588                             Label& skip_fixup,
 589                             address start,
 590                             OopMapSet* oop_maps,
 591                             int& frame_complete,
 592                             int& frame_size_in_words,
 593                             bool alloc_inline_receiver) {
 594   if (requires_clinit_barrier && VM_Version::supports_fast_class_init_checks()) {
 595     Label L_skip_barrier;
 596 
 597     { // Bypass the barrier for non-static methods
 598       __ ldrh(rscratch1, Address(rmethod, Method::access_flags_offset()));
 599       __ andsw(zr, rscratch1, JVM_ACC_STATIC);
 600       __ br(Assembler::EQ, L_skip_barrier); // non-static
 601     }
 602 
 603     __ load_method_holder(rscratch2, rmethod);
 604     __ clinit_barrier(rscratch2, rscratch1, &L_skip_barrier);
 605     __ far_jump(RuntimeAddress(SharedRuntime::get_handle_wrong_method_stub()));
 606 
 607     __ bind(L_skip_barrier);
 608     c2i_no_clinit_check_entry = __ pc();
 609   }
 610 
 611   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
 612   bs->c2i_entry_barrier(masm);
 613 
 614   // Before we get into the guts of the C2I adapter, see if we should be here
 615   // at all.  We've come from compiled code and are attempting to jump to the
 616   // interpreter, which means the caller made a static call to get here
 617   // (vcalls always get a compiled target if there is one).  Check for a
 618   // compiled target.  If there is one, we need to patch the caller's call.
 619   patch_callers_callsite(masm);
 620 
 621   __ bind(skip_fixup);
 622 
 623   // TODO 8366717 Is the comment about r13 correct? Isn't that r19_sender_sp?
 624   // Name some registers to be used in the following code. We can use
 625   // anything except r0-r7 which are arguments in the Java calling
 626   // convention, rmethod (r12), and r13 which holds the outgoing sender
 627   // SP for the interpreter.
 628   // TODO 8366717 We need to make sure that buf_array, buf_oop (and potentially other long-life regs) are kept live in slowpath runtime calls in GC barriers
 629   Register buf_array = r10;   // Array of buffered inline types
 630   Register buf_oop = r11;     // Buffered inline type oop
 631   Register tmp1 = r15;
 632   Register tmp2 = r16;
 633   Register tmp3 = r17;
 634 
 635   if (InlineTypePassFieldsAsArgs) {
 636     // Is there an inline type argument?
 637     bool has_inline_argument = false;
 638     for (int i = 0; i < sig_extended->length() && !has_inline_argument; i++) {
 639       has_inline_argument = (sig_extended->at(i)._bt == T_METADATA);
 640     }
 641     if (has_inline_argument) {
 642       // There is at least an inline type argument: we're coming from
 643       // compiled code so we have no buffers to back the inline types
 644       // Allocate the buffers here with a runtime call.
 645       // TODO 8366717 Do we need to save vectors here? They could be used as arg registers, right? Same on x64.
 646       RegisterSaver reg_save(true /* save_vectors */);
 647       OopMap* map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
 648 
 649       frame_complete = __ offset();
 650       address the_pc = __ pc();
 651 
 652       Label retaddr;
 653       __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
 654 
 655       __ mov(c_rarg0, rthread);
 656       __ mov(c_rarg1, rmethod);
 657       __ mov(c_rarg2, (int64_t)alloc_inline_receiver);
 658 
 659       __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::allocate_inline_types)));
 660       __ blr(rscratch1);
 661       __ bind(retaddr);
 662 
 663       oop_maps->add_gc_map(__ pc() - start, map);
 664       __ reset_last_Java_frame(false);
 665 
 666       reg_save.restore_live_registers(masm);





 667 
 668       Label no_exception;
 669       __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
 670       __ cbz(rscratch1, no_exception);













 671 
 672       __ str(zr, Address(rthread, JavaThread::vm_result_oop_offset()));
 673       __ ldr(r0, Address(rthread, Thread::pending_exception_offset()));
 674       __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
 675 
 676       __ bind(no_exception);
 677 
 678       // We get an array of objects from the runtime call
 679       __ get_vm_result_oop(buf_array, rthread);
 680       __ get_vm_result_metadata(rmethod, rthread); // TODO: required to keep the callee Method live?
 681     }
 682   }








 683 
 684   // Since all args are passed on the stack, total_args_passed *
 685   // Interpreter::stackElementSize is the space we need.
 686 
 687   int total_args_passed = compute_total_args_passed_int(sig_extended);
 688   int extraspace = total_args_passed * Interpreter::stackElementSize;
 689 
 690   // stack is aligned, keep it that way
 691   extraspace = align_up(extraspace, StackAlignmentInBytes);
 692 
 693   // set senderSP value
 694   __ mov(r19_sender_sp, sp);
 695 
 696   __ sub(sp, sp, extraspace);
 697 
 698   // Now write the args into the outgoing interpreter space
 699 
 700   // next_arg_comp is the next argument from the compiler point of
 701   // view (inline type fields are passed in registers/on the stack). In
 702   // sig_extended, an inline type argument starts with: T_METADATA,
 703   // followed by the types of the fields of the inline type and T_VOID
 704   // to mark the end of the inline type. ignored counts the number of
 705   // T_METADATA/T_VOID. next_vt_arg is the next inline type argument:
 706   // used to get the buffer for that argument from the pool of buffers
 707   // we allocated above and want to pass to the
 708   // interpreter. next_arg_int is the next argument from the
 709   // interpreter point of view (inline types are passed by reference).
 710   for (int next_arg_comp = 0, ignored = 0, next_vt_arg = 0, next_arg_int = 0;
 711        next_arg_comp < sig_extended->length(); next_arg_comp++) {
 712     assert(ignored <= next_arg_comp, "shouldn't skip over more slots than there are arguments");
 713     assert(next_arg_int <= total_args_passed, "more arguments for the interpreter than expected?");
 714     BasicType bt = sig_extended->at(next_arg_comp)._bt;
 715     int st_off = (total_args_passed - next_arg_int - 1) * Interpreter::stackElementSize;
 716     if (!InlineTypePassFieldsAsArgs || bt != T_METADATA) {
 717       int next_off = st_off - Interpreter::stackElementSize;
 718       const int offset = (bt == T_LONG || bt == T_DOUBLE) ? next_off : st_off;
 719       const VMRegPair reg_pair = regs[next_arg_comp-ignored];
 720       size_t size_in_bytes = reg_pair.second()->is_valid() ? 8 : 4;
 721       gen_c2i_adapter_helper(masm, bt, next_arg_comp > 0 ? sig_extended->at(next_arg_comp-1)._bt : T_ILLEGAL,
 722                              size_in_bytes, reg_pair, Address(sp, offset), tmp1, tmp2, tmp3, extraspace, false);
 723       next_arg_int++;
 724 #ifdef ASSERT
 725       if (bt == T_LONG || bt == T_DOUBLE) {
 726         // Overwrite the unused slot with known junk
 727         __ mov(rscratch1, CONST64(0xdeadffffdeadaaaa));
 728         __ str(rscratch1, Address(sp, st_off));



 729       }















 730 #endif /* ASSERT */
 731     } else {
 732       ignored++;
 733       // get the buffer from the just allocated pool of buffers
 734       int index = arrayOopDesc::base_offset_in_bytes(T_OBJECT) + next_vt_arg * type2aelembytes(T_OBJECT);
 735       __ load_heap_oop(buf_oop, Address(buf_array, index), tmp1, tmp2);
 736       next_vt_arg++; next_arg_int++;
 737       int vt = 1;
 738       // write fields we get from compiled code in registers/stack
 739       // slots to the buffer: we know we are done with that inline type
 740       // argument when we hit the T_VOID that acts as an end of inline
 741       // type delimiter for this inline type. Inline types are flattened
 742       // so we might encounter embedded inline types. Each entry in
 743       // sig_extended contains a field offset in the buffer.
 744       Label L_null;
 745       do {
 746         next_arg_comp++;
 747         BasicType bt = sig_extended->at(next_arg_comp)._bt;
 748         BasicType prev_bt = sig_extended->at(next_arg_comp - 1)._bt;
 749         if (bt == T_METADATA) {
 750           vt++;
 751           ignored++;
 752         } else if (bt == T_VOID && prev_bt != T_LONG && prev_bt != T_DOUBLE) {
 753           vt--;
 754           ignored++;
 755         } else {
 756           int off = sig_extended->at(next_arg_comp)._offset;
 757           if (off == -1) {
 758             // Nullable inline type argument, emit null check
 759             VMReg reg = regs[next_arg_comp-ignored].first();
 760             Label L_notNull;
 761             if (reg->is_stack()) {
 762               int ld_off = reg->reg2stack() * VMRegImpl::stack_slot_size + extraspace;
 763               __ ldrb(tmp1, Address(sp, ld_off));
 764               __ cbnz(tmp1, L_notNull);
 765             } else {
 766               __ cbnz(reg->as_Register(), L_notNull);
 767             }
 768             __ str(zr, Address(sp, st_off));
 769             __ b(L_null);
 770             __ bind(L_notNull);
 771             continue;
 772           }
 773           assert(off > 0, "offset in object should be positive");
 774           size_t size_in_bytes = is_java_primitive(bt) ? type2aelembytes(bt) : wordSize;
 775           bool is_oop = is_reference_type(bt);
 776           gen_c2i_adapter_helper(masm, bt, next_arg_comp > 0 ? sig_extended->at(next_arg_comp-1)._bt : T_ILLEGAL,
 777                                  size_in_bytes, regs[next_arg_comp-ignored], Address(buf_oop, off), tmp1, tmp2, tmp3, extraspace, is_oop);
 778         }
 779       } while (vt != 0);
 780       // pass the buffer to the interpreter
 781       __ str(buf_oop, Address(sp, st_off));
 782       __ bind(L_null);










 783     }
 784   }
 785 
 786   __ mov(esp, sp); // Interp expects args on caller's expression stack
 787 
 788   __ ldr(rscratch1, Address(rmethod, in_bytes(Method::interpreter_entry_offset())));
 789   __ br(rscratch1);
 790 }
 791 
 792 void SharedRuntime::gen_i2c_adapter(MacroAssembler *masm, int comp_args_on_stack, const GrowableArray<SigEntry>* sig, const VMRegPair *regs) {
 793 





 794 
 795   // Note: r19_sender_sp contains the senderSP on entry. We must
 796   // preserve it since we may do a i2c -> c2i transition if we lose a
 797   // race where compiled code goes non-entrant while we get args
 798   // ready.
 799 
 800   // Adapters are frameless.
 801 
 802   // An i2c adapter is frameless because the *caller* frame, which is
 803   // interpreted, routinely repairs its own esp (from
 804   // interpreter_frame_last_sp), even if a callee has modified the
 805   // stack pointer.  It also recalculates and aligns sp.
 806 
 807   // A c2i adapter is frameless because the *callee* frame, which is
 808   // interpreted, routinely repairs its caller's sp (from sender_sp,
 809   // which is set up via the senderSP register).
 810 
 811   // In other words, if *either* the caller or callee is interpreted, we can
 812   // get the stack pointer repaired after a call.
 813 
 814   // This is why c2i and i2c adapters cannot be indefinitely composed.
 815   // In particular, if a c2i adapter were to somehow call an i2c adapter,
 816   // both caller and callee would be compiled methods, and neither would
 817   // clean up the stack pointer changes performed by the two adapters.
 818   // If this happens, control eventually transfers back to the compiled
 819   // caller, but with an uncorrected stack, causing delayed havoc.
 820 
 821   // Cut-out for having no stack args.
 822   int comp_words_on_stack = 0;
 823   if (comp_args_on_stack) {
 824      comp_words_on_stack = align_up(comp_args_on_stack * VMRegImpl::stack_slot_size, wordSize) >> LogBytesPerWord;
 825      __ sub(rscratch1, sp, comp_words_on_stack * wordSize);
 826      __ andr(sp, rscratch1, -16);
 827   }
 828 
 829   // Will jump to the compiled code just as if compiled code was doing it.
 830   // Pre-load the register-jump target early, to schedule it better.
 831   __ ldr(rscratch1, Address(rmethod, in_bytes(Method::from_compiled_inline_offset())));
 832 
 833 #if INCLUDE_JVMCI
 834   if (EnableJVMCI) {
 835     // check if this call should be routed towards a specific entry point
 836     __ ldr(rscratch2, Address(rthread, in_bytes(JavaThread::jvmci_alternate_call_target_offset())));
 837     Label no_alternative_target;
 838     __ cbz(rscratch2, no_alternative_target);
 839     __ mov(rscratch1, rscratch2);
 840     __ str(zr, Address(rthread, in_bytes(JavaThread::jvmci_alternate_call_target_offset())));
 841     __ bind(no_alternative_target);
 842   }
 843 #endif // INCLUDE_JVMCI
 844 
 845   int total_args_passed = sig->length();
 846 
 847   // Now generate the shuffle code.
 848   for (int i = 0; i < total_args_passed; i++) {
 849     BasicType bt = sig->at(i)._bt;
 850     if (bt == T_VOID) {
 851       assert(i > 0 && (sig->at(i - 1)._bt == T_LONG || sig->at(i - 1)._bt == T_DOUBLE), "missing half");
 852       continue;
 853     }
 854 
 855     // Pick up 0, 1 or 2 words from SP+offset.
 856     assert(!regs[i].second()->is_valid() || regs[i].first()->next() == regs[i].second(), "scrambled load targets?");
 857 


 858     // Load in argument order going down.
 859     int ld_off = (total_args_passed - i - 1) * Interpreter::stackElementSize;
 860     // Point to interpreter value (vs. tag)
 861     int next_off = ld_off - Interpreter::stackElementSize;
 862     //
 863     //
 864     //
 865     VMReg r_1 = regs[i].first();
 866     VMReg r_2 = regs[i].second();
 867     if (!r_1->is_valid()) {
 868       assert(!r_2->is_valid(), "");
 869       continue;
 870     }
 871     if (r_1->is_stack()) {
 872       // Convert stack slot to an SP offset (+ wordSize to account for return address )
 873       int st_off = regs[i].first()->reg2stack() * VMRegImpl::stack_slot_size;
 874       if (!r_2->is_valid()) {
 875         // sign extend???
 876         __ ldrsw(rscratch2, Address(esp, ld_off));
 877         __ str(rscratch2, Address(sp, st_off));
 878       } else {
 879         //
 880         // We are using two optoregs. This can be either T_OBJECT,
 881         // T_ADDRESS, T_LONG, or T_DOUBLE the interpreter allocates
 882         // two slots but only uses one for thr T_LONG or T_DOUBLE case
 883         // So we must adjust where to pick up the data to match the
 884         // interpreter.
 885         //
 886         // Interpreter local[n] == MSW, local[n+1] == LSW however locals
 887         // are accessed as negative so LSW is at LOW address
 888 
 889         // ld_off is MSW so get LSW
 890         const int offset = (bt == T_LONG || bt == T_DOUBLE) ? next_off : ld_off;

 891         __ ldr(rscratch2, Address(esp, offset));
 892         // st_off is LSW (i.e. reg.first())
 893          __ str(rscratch2, Address(sp, st_off));
 894        }
 895      } else if (r_1->is_Register()) {  // Register argument
 896        Register r = r_1->as_Register();
 897        if (r_2->is_valid()) {
 898          //
 899          // We are using two VMRegs. This can be either T_OBJECT,
 900          // T_ADDRESS, T_LONG, or T_DOUBLE the interpreter allocates
 901          // two slots but only uses one for thr T_LONG or T_DOUBLE case
 902          // So we must adjust where to pick up the data to match the
 903          // interpreter.
 904 
 905         const int offset = (bt == T_LONG || bt == T_DOUBLE) ? next_off : ld_off;
 906 
 907          // this can be a misaligned move
 908          __ ldr(r, Address(esp, offset));
 909        } else {
 910          // sign extend and use a full word?
 911          __ ldrw(r, Address(esp, ld_off));
 912        }
 913      } else {
 914        if (!r_2->is_valid()) {
 915          __ ldrs(r_1->as_FloatRegister(), Address(esp, ld_off));
 916        } else {
 917          __ ldrd(r_1->as_FloatRegister(), Address(esp, next_off));
 918        }
 919      }
 920    }
 921 

















 922 
 923   __ mov(rscratch2, rscratch1);
 924   __ push_cont_fastpath(rthread); // Set JavaThread::_cont_fastpath to the sp of the oldest interpreted frame we know about; kills rscratch1
 925   __ mov(rscratch1, rscratch2);
 926 
 927   // 6243940 We might end up in handle_wrong_method if
 928   // the callee is deoptimized as we race thru here. If that
 929   // happens we don't want to take a safepoint because the
 930   // caller frame will look interpreted and arguments are now
 931   // "compiled" so it is much better to make this transition
 932   // invisible to the stack walking code. Unfortunately if
 933   // we try and find the callee by normal means a safepoint
 934   // is possible. So we stash the desired callee in the thread
 935   // and the vm will find there should this case occur.
 936 
 937   __ str(rmethod, Address(rthread, JavaThread::callee_target_offset()));

 938   __ br(rscratch1);
 939 }
 940 
 941 static void gen_inline_cache_check(MacroAssembler *masm, Label& skip_fixup) {
 942   Register data = rscratch2;
 943   __ ic_check(1 /* end_alignment */);
 944   __ ldr(rmethod, Address(data, CompiledICData::speculated_method_offset()));




 945 
 946   // Method might have been compiled since the call site was patched to
 947   // interpreted; if that is the case treat it as a miss so we can get
 948   // the call site corrected.
 949   __ ldr(rscratch1, Address(rmethod, in_bytes(Method::code_offset())));
 950   __ cbz(rscratch1, skip_fixup);
 951   __ far_jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 952 }
 953 
 954 // ---------------------------------------------------------------
 955 void SharedRuntime::generate_i2c2i_adapters(MacroAssembler* masm,
 956                                             int comp_args_on_stack,
 957                                             const GrowableArray<SigEntry>* sig,
 958                                             const VMRegPair* regs,
 959                                             const GrowableArray<SigEntry>* sig_cc,
 960                                             const VMRegPair* regs_cc,
 961                                             const GrowableArray<SigEntry>* sig_cc_ro,
 962                                             const VMRegPair* regs_cc_ro,
 963                                             address entry_address[AdapterBlob::ENTRY_COUNT],
 964                                             AdapterBlob*& new_adapter,
 965                                             bool allocate_code_blob) {
 966 
 967   entry_address[AdapterBlob::I2C] = __ pc();
 968   gen_i2c_adapter(masm, comp_args_on_stack, sig, regs);

 969 
 970   // -------------------------------------------------------------------------
 971   // Generate a C2I adapter.  On entry we know rmethod holds the Method* during calls
 972   // to the interpreter.  The args start out packed in the compiled layout.  They
 973   // need to be unpacked into the interpreter layout.  This will almost always
 974   // require some stack space.  We grow the current (compiled) stack, then repack
 975   // the args.  We  finally end in a jump to the generic interpreter entry point.
 976   // On exit from the interpreter, the interpreter will restore our SP (lest the
 977   // compiled code, which relies solely on SP and not FP, get sick).
 978 
 979   entry_address[AdapterBlob::C2I_Unverified] = __ pc();
 980   entry_address[AdapterBlob::C2I_Unverified_Inline] = __ pc();
 981   Label skip_fixup;




 982 
 983   gen_inline_cache_check(masm, skip_fixup);




 984 
 985   OopMapSet* oop_maps = new OopMapSet();
 986   int frame_complete = CodeOffsets::frame_never_safe;
 987   int frame_size_in_words = 0;
 988 
 989   // Scalarized c2i adapter with non-scalarized receiver (i.e., don't pack receiver)
 990   entry_address[AdapterBlob::C2I_No_Clinit_Check] = nullptr;
 991   entry_address[AdapterBlob::C2I_Inline_RO] = __ pc();
 992   if (regs_cc != regs_cc_ro) {
 993     // No class init barrier needed because method is guaranteed to be non-static
 994     gen_c2i_adapter(masm, sig_cc_ro, regs_cc_ro, /* requires_clinit_barrier = */ false, entry_address[AdapterBlob::C2I_No_Clinit_Check],
 995                     skip_fixup, entry_address[AdapterBlob::I2C], oop_maps, frame_complete, frame_size_in_words, /* alloc_inline_receiver = */ false);
 996     skip_fixup.reset();
 997   }
 998 
 999   // Scalarized c2i adapter
1000   entry_address[AdapterBlob::C2I]        = __ pc();
1001   entry_address[AdapterBlob::C2I_Inline] = __ pc();
1002   gen_c2i_adapter(masm, sig_cc, regs_cc, /* requires_clinit_barrier = */ true, entry_address[AdapterBlob::C2I_No_Clinit_Check],
1003                   skip_fixup, entry_address[AdapterBlob::I2C], oop_maps, frame_complete, frame_size_in_words, /* alloc_inline_receiver = */ true);
1004 
1005   // Non-scalarized c2i adapter
1006   if (regs != regs_cc) {
1007     entry_address[AdapterBlob::C2I_Unverified_Inline] = __ pc();
1008     Label inline_entry_skip_fixup;
1009     gen_inline_cache_check(masm, inline_entry_skip_fixup);
1010 
1011     entry_address[AdapterBlob::C2I_Inline] = __ pc();
1012     gen_c2i_adapter(masm, sig, regs, /* requires_clinit_barrier = */ true, entry_address[AdapterBlob::C2I_No_Clinit_Check],
1013                     inline_entry_skip_fixup, entry_address[AdapterBlob::I2C], oop_maps, frame_complete, frame_size_in_words, /* alloc_inline_receiver = */ false);
1014   }
1015 
1016   // The c2i adapters might safepoint and trigger a GC. The caller must make sure that
1017   // the GC knows about the location of oop argument locations passed to the c2i adapter.
1018   if (allocate_code_blob) {
1019     bool caller_must_gc_arguments = (regs != regs_cc);
1020     int entry_offset[AdapterHandlerEntry::ENTRIES_COUNT];
1021     assert(AdapterHandlerEntry::ENTRIES_COUNT == 7, "sanity");
1022     AdapterHandlerLibrary::address_to_offset(entry_address, entry_offset);
1023     new_adapter = AdapterBlob::create(masm->code(), entry_offset, frame_complete, frame_size_in_words, oop_maps, caller_must_gc_arguments);
1024   }






1025 }
1026 
1027 static int c_calling_convention_priv(const BasicType *sig_bt,
1028                                          VMRegPair *regs,
1029                                          int total_args_passed) {
1030 
1031 // We return the amount of VMRegImpl stack slots we need to reserve for all
1032 // the arguments NOT counting out_preserve_stack_slots.
1033 
1034     static const Register INT_ArgReg[Argument::n_int_register_parameters_c] = {
1035       c_rarg0, c_rarg1, c_rarg2, c_rarg3, c_rarg4, c_rarg5,  c_rarg6,  c_rarg7
1036     };
1037     static const FloatRegister FP_ArgReg[Argument::n_float_register_parameters_c] = {
1038       c_farg0, c_farg1, c_farg2, c_farg3,
1039       c_farg4, c_farg5, c_farg6, c_farg7
1040     };
1041 
1042     uint int_args = 0;
1043     uint fp_args = 0;
1044     uint stk_args = 0; // inc by 2 each time
1045 
1046     for (int i = 0; i < total_args_passed; i++) {
1047       switch (sig_bt[i]) {
1048       case T_BOOLEAN:
1049       case T_CHAR:
1050       case T_BYTE:
1051       case T_SHORT:
1052       case T_INT:
1053         if (int_args < Argument::n_int_register_parameters_c) {
1054           regs[i].set1(INT_ArgReg[int_args++]->as_VMReg());
1055         } else {
1056 #ifdef __APPLE__
1057           // Less-than word types are stored one after another.
1058           // The code is unable to handle this so bailout.
1059           return -1;
1060 #endif
1061           regs[i].set1(VMRegImpl::stack2reg(stk_args));
1062           stk_args += 2;
1063         }
1064         break;
1065       case T_LONG:
1066         assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
1067         // fall through
1068       case T_OBJECT:
1069       case T_ARRAY:
1070       case T_ADDRESS:
1071       case T_METADATA:
1072         if (int_args < Argument::n_int_register_parameters_c) {
1073           regs[i].set2(INT_ArgReg[int_args++]->as_VMReg());
1074         } else {
1075           regs[i].set2(VMRegImpl::stack2reg(stk_args));
1076           stk_args += 2;
1077         }
1078         break;
1079       case T_FLOAT:
1080         if (fp_args < Argument::n_float_register_parameters_c) {
1081           regs[i].set1(FP_ArgReg[fp_args++]->as_VMReg());
1082         } else {
1083 #ifdef __APPLE__
1084           // Less-than word types are stored one after another.
1085           // The code is unable to handle this so bailout.
1086           return -1;
1087 #endif
1088           regs[i].set1(VMRegImpl::stack2reg(stk_args));
1089           stk_args += 2;
1090         }
1091         break;
1092       case T_DOUBLE:
1093         assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
1094         if (fp_args < Argument::n_float_register_parameters_c) {
1095           regs[i].set2(FP_ArgReg[fp_args++]->as_VMReg());
1096         } else {
1097           regs[i].set2(VMRegImpl::stack2reg(stk_args));
1098           stk_args += 2;
1099         }
1100         break;
1101       case T_VOID: // Halves of longs and doubles
1102         assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
1103         regs[i].set_bad();
1104         break;
1105       default:
1106         ShouldNotReachHere();
1107         break;
1108       }
1109     }
1110 
1111   return stk_args;
1112 }
1113 
1114 int SharedRuntime::vector_calling_convention(VMRegPair *regs,
1115                                              uint num_bits,
1116                                              uint total_args_passed) {
1117   // More than 8 argument inputs are not supported now.
1118   assert(total_args_passed <= Argument::n_float_register_parameters_c, "unsupported");
1119   assert(num_bits >= 64 && num_bits <= 2048 && is_power_of_2(num_bits), "unsupported");
1120 
1121   static const FloatRegister VEC_ArgReg[Argument::n_float_register_parameters_c] = {
1122     v0, v1, v2, v3, v4, v5, v6, v7
1123   };
1124 
1125   // On SVE, we use the same vector registers with 128-bit vector registers on NEON.
1126   int next_reg_val = num_bits == 64 ? 1 : 3;
1127   for (uint i = 0; i < total_args_passed; i++) {
1128     VMReg vmreg = VEC_ArgReg[i]->as_VMReg();
1129     regs[i].set_pair(vmreg->next(next_reg_val), vmreg);
1130   }
1131   return 0;
1132 }
1133 
1134 int SharedRuntime::c_calling_convention(const BasicType *sig_bt,
1135                                          VMRegPair *regs,
1136                                          int total_args_passed)
1137 {
1138   int result = c_calling_convention_priv(sig_bt, regs, total_args_passed);
1139   guarantee(result >= 0, "Unsupported arguments configuration");
1140   return result;
1141 }
1142 
1143 
1144 void SharedRuntime::save_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1145   // We always ignore the frame_slots arg and just use the space just below frame pointer
1146   // which by this time is free to use
1147   switch (ret_type) {
1148   case T_FLOAT:
1149     __ strs(v0, Address(rfp, -wordSize));
1150     break;
1151   case T_DOUBLE:
1152     __ strd(v0, Address(rfp, -wordSize));
1153     break;
1154   case T_VOID:  break;
1155   default: {
1156     __ str(r0, Address(rfp, -wordSize));
1157     }
1158   }
1159 }
1160 
1161 void SharedRuntime::restore_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1162   // We always ignore the frame_slots arg and just use the space just below frame pointer
1163   // which by this time is free to use
1164   switch (ret_type) {
1165   case T_FLOAT:
1166     __ ldrs(v0, Address(rfp, -wordSize));
1167     break;
1168   case T_DOUBLE:
1169     __ ldrd(v0, Address(rfp, -wordSize));
1170     break;
1171   case T_VOID:  break;
1172   default: {
1173     __ ldr(r0, Address(rfp, -wordSize));
1174     }
1175   }
1176 }
1177 static void save_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
1178   RegSet x;
1179   for ( int i = first_arg ; i < arg_count ; i++ ) {
1180     if (args[i].first()->is_Register()) {
1181       x = x + args[i].first()->as_Register();
1182     } else if (args[i].first()->is_FloatRegister()) {
1183       __ strd(args[i].first()->as_FloatRegister(), Address(__ pre(sp, -2 * wordSize)));
1184     }
1185   }
1186   __ push(x, sp);
1187 }
1188 
1189 static void restore_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
1190   RegSet x;
1191   for ( int i = first_arg ; i < arg_count ; i++ ) {
1192     if (args[i].first()->is_Register()) {
1193       x = x + args[i].first()->as_Register();
1194     } else {
1195       ;
1196     }
1197   }
1198   __ pop(x, sp);
1199   for ( int i = arg_count - 1 ; i >= first_arg ; i-- ) {
1200     if (args[i].first()->is_Register()) {
1201       ;
1202     } else if (args[i].first()->is_FloatRegister()) {
1203       __ ldrd(args[i].first()->as_FloatRegister(), Address(__ post(sp, 2 * wordSize)));
1204     }
1205   }
1206 }
1207 
1208 static void verify_oop_args(MacroAssembler* masm,
1209                             const methodHandle& method,
1210                             const BasicType* sig_bt,
1211                             const VMRegPair* regs) {
1212   Register temp_reg = r19;  // not part of any compiled calling seq
1213   if (VerifyOops) {
1214     for (int i = 0; i < method->size_of_parameters(); i++) {
1215       if (sig_bt[i] == T_OBJECT ||
1216           sig_bt[i] == T_ARRAY) {
1217         VMReg r = regs[i].first();
1218         assert(r->is_valid(), "bad oop arg");
1219         if (r->is_stack()) {
1220           __ ldr(temp_reg, Address(sp, r->reg2stack() * VMRegImpl::stack_slot_size));
1221           __ verify_oop(temp_reg);
1222         } else {
1223           __ verify_oop(r->as_Register());
1224         }
1225       }
1226     }
1227   }
1228 }
1229 
1230 // on exit, sp points to the ContinuationEntry
1231 static OopMap* continuation_enter_setup(MacroAssembler* masm, int& stack_slots) {
1232   assert(ContinuationEntry::size() % VMRegImpl::stack_slot_size == 0, "");
1233   assert(in_bytes(ContinuationEntry::cont_offset())  % VMRegImpl::stack_slot_size == 0, "");
1234   assert(in_bytes(ContinuationEntry::chunk_offset()) % VMRegImpl::stack_slot_size == 0, "");
1235 
1236   stack_slots += (int)ContinuationEntry::size()/wordSize;
1237   __ sub(sp, sp, (int)ContinuationEntry::size()); // place Continuation metadata
1238 
1239   OopMap* map = new OopMap(((int)ContinuationEntry::size() + wordSize)/ VMRegImpl::stack_slot_size, 0 /* arg_slots*/);
1240 
1241   __ ldr(rscratch1, Address(rthread, JavaThread::cont_entry_offset()));
1242   __ str(rscratch1, Address(sp, ContinuationEntry::parent_offset()));
1243   __ mov(rscratch1, sp); // we can't use sp as the source in str
1244   __ str(rscratch1, Address(rthread, JavaThread::cont_entry_offset()));
1245 
1246   return map;
1247 }
1248 
1249 // on entry c_rarg1 points to the continuation
1250 //          sp points to ContinuationEntry
1251 //          c_rarg3 -- isVirtualThread
1252 static void fill_continuation_entry(MacroAssembler* masm) {
1253 #ifdef ASSERT
1254   __ movw(rscratch1, ContinuationEntry::cookie_value());
1255   __ strw(rscratch1, Address(sp, ContinuationEntry::cookie_offset()));
1256 #endif
1257 
1258   __ str (c_rarg1, Address(sp, ContinuationEntry::cont_offset()));
1259   __ strw(c_rarg3, Address(sp, ContinuationEntry::flags_offset()));
1260   __ str (zr,      Address(sp, ContinuationEntry::chunk_offset()));
1261   __ strw(zr,      Address(sp, ContinuationEntry::argsize_offset()));
1262   __ strw(zr,      Address(sp, ContinuationEntry::pin_count_offset()));
1263 
1264   __ ldr(rscratch1, Address(rthread, JavaThread::cont_fastpath_offset()));
1265   __ str(rscratch1, Address(sp, ContinuationEntry::parent_cont_fastpath_offset()));
1266   __ ldr(rscratch1, Address(rthread, JavaThread::held_monitor_count_offset()));
1267   __ str(rscratch1, Address(sp, ContinuationEntry::parent_held_monitor_count_offset()));
1268 
1269   __ str(zr, Address(rthread, JavaThread::cont_fastpath_offset()));
1270   __ str(zr, Address(rthread, JavaThread::held_monitor_count_offset()));
1271 }
1272 
1273 // on entry, sp points to the ContinuationEntry
1274 // on exit, rfp points to the spilled rfp in the entry frame
1275 static void continuation_enter_cleanup(MacroAssembler* masm) {
1276 #ifndef PRODUCT
1277   Label OK;
1278   __ ldr(rscratch1, Address(rthread, JavaThread::cont_entry_offset()));
1279   __ cmp(sp, rscratch1);
1280   __ br(Assembler::EQ, OK);
1281   __ stop("incorrect sp1");
1282   __ bind(OK);
1283 #endif
1284   __ ldr(rscratch1, Address(sp, ContinuationEntry::parent_cont_fastpath_offset()));
1285   __ str(rscratch1, Address(rthread, JavaThread::cont_fastpath_offset()));
1286 
1287   if (CheckJNICalls) {
1288     // Check if this is a virtual thread continuation
1289     Label L_skip_vthread_code;
1290     __ ldrw(rscratch1, Address(sp, ContinuationEntry::flags_offset()));
1291     __ cbzw(rscratch1, L_skip_vthread_code);
1292 
1293     // If the held monitor count is > 0 and this vthread is terminating then
1294     // it failed to release a JNI monitor. So we issue the same log message
1295     // that JavaThread::exit does.
1296     __ ldr(rscratch1, Address(rthread, JavaThread::jni_monitor_count_offset()));
1297     __ cbz(rscratch1, L_skip_vthread_code);
1298 
1299     // Save return value potentially containing the exception oop in callee-saved R19.
1300     __ mov(r19, r0);
1301     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::log_jni_monitor_still_held));
1302     // Restore potential return value.
1303     __ mov(r0, r19);
1304 
1305     // For vthreads we have to explicitly zero the JNI monitor count of the carrier
1306     // on termination. The held count is implicitly zeroed below when we restore from
1307     // the parent held count (which has to be zero).
1308     __ str(zr, Address(rthread, JavaThread::jni_monitor_count_offset()));
1309 
1310     __ bind(L_skip_vthread_code);
1311   }
1312 #ifdef ASSERT
1313   else {
1314     // Check if this is a virtual thread continuation
1315     Label L_skip_vthread_code;
1316     __ ldrw(rscratch1, Address(sp, ContinuationEntry::flags_offset()));
1317     __ cbzw(rscratch1, L_skip_vthread_code);
1318 
1319     // See comment just above. If not checking JNI calls the JNI count is only
1320     // needed for assertion checking.
1321     __ str(zr, Address(rthread, JavaThread::jni_monitor_count_offset()));
1322 
1323     __ bind(L_skip_vthread_code);
1324   }
1325 #endif
1326 
1327   __ ldr(rscratch1, Address(sp, ContinuationEntry::parent_held_monitor_count_offset()));
1328   __ str(rscratch1, Address(rthread, JavaThread::held_monitor_count_offset()));
1329 
1330   __ ldr(rscratch2, Address(sp, ContinuationEntry::parent_offset()));
1331   __ str(rscratch2, Address(rthread, JavaThread::cont_entry_offset()));
1332   __ add(rfp, sp, (int)ContinuationEntry::size());
1333 }
1334 
1335 // enterSpecial(Continuation c, boolean isContinue, boolean isVirtualThread)
1336 // On entry: c_rarg1 -- the continuation object
1337 //           c_rarg2 -- isContinue
1338 //           c_rarg3 -- isVirtualThread
1339 static void gen_continuation_enter(MacroAssembler* masm,
1340                                  const methodHandle& method,
1341                                  const BasicType* sig_bt,
1342                                  const VMRegPair* regs,
1343                                  int& exception_offset,
1344                                  OopMapSet*oop_maps,
1345                                  int& frame_complete,
1346                                  int& stack_slots,
1347                                  int& interpreted_entry_offset,
1348                                  int& compiled_entry_offset) {
1349   //verify_oop_args(masm, method, sig_bt, regs);
1350   Address resolve(SharedRuntime::get_resolve_static_call_stub(), relocInfo::static_call_type);
1351 
1352   address start = __ pc();
1353 
1354   Label call_thaw, exit;
1355 
1356   // i2i entry used at interp_only_mode only
1357   interpreted_entry_offset = __ pc() - start;
1358   {
1359 
1360 #ifdef ASSERT
1361     Label is_interp_only;
1362     __ ldrw(rscratch1, Address(rthread, JavaThread::interp_only_mode_offset()));
1363     __ cbnzw(rscratch1, is_interp_only);
1364     __ stop("enterSpecial interpreter entry called when not in interp_only_mode");
1365     __ bind(is_interp_only);
1366 #endif
1367 
1368     // Read interpreter arguments into registers (this is an ad-hoc i2c adapter)
1369     __ ldr(c_rarg1, Address(esp, Interpreter::stackElementSize*2));
1370     __ ldr(c_rarg2, Address(esp, Interpreter::stackElementSize*1));
1371     __ ldr(c_rarg3, Address(esp, Interpreter::stackElementSize*0));
1372     __ push_cont_fastpath(rthread);
1373 
1374     __ enter();
1375     stack_slots = 2; // will be adjusted in setup
1376     OopMap* map = continuation_enter_setup(masm, stack_slots);
1377     // The frame is complete here, but we only record it for the compiled entry, so the frame would appear unsafe,
1378     // but that's okay because at the very worst we'll miss an async sample, but we're in interp_only_mode anyway.
1379 
1380     fill_continuation_entry(masm);
1381 
1382     __ cbnz(c_rarg2, call_thaw);
1383 
1384     const address tr_call = __ trampoline_call(resolve);
1385     if (tr_call == nullptr) {
1386       fatal("CodeCache is full at gen_continuation_enter");
1387     }
1388 
1389     oop_maps->add_gc_map(__ pc() - start, map);
1390     __ post_call_nop();
1391 
1392     __ b(exit);
1393 
1394     address stub = CompiledDirectCall::emit_to_interp_stub(masm, tr_call);
1395     if (stub == nullptr) {
1396       fatal("CodeCache is full at gen_continuation_enter");
1397     }
1398   }
1399 
1400   // compiled entry
1401   __ align(CodeEntryAlignment);
1402   compiled_entry_offset = __ pc() - start;
1403 
1404   __ enter();
1405   stack_slots = 2; // will be adjusted in setup
1406   OopMap* map = continuation_enter_setup(masm, stack_slots);
1407   frame_complete = __ pc() - start;
1408 
1409   fill_continuation_entry(masm);
1410 
1411   __ cbnz(c_rarg2, call_thaw);
1412 
1413   const address tr_call = __ trampoline_call(resolve);
1414   if (tr_call == nullptr) {
1415     fatal("CodeCache is full at gen_continuation_enter");
1416   }
1417 
1418   oop_maps->add_gc_map(__ pc() - start, map);
1419   __ post_call_nop();
1420 
1421   __ b(exit);
1422 
1423   __ bind(call_thaw);
1424 
1425   ContinuationEntry::_thaw_call_pc_offset = __ pc() - start;
1426   __ rt_call(CAST_FROM_FN_PTR(address, StubRoutines::cont_thaw()));
1427   oop_maps->add_gc_map(__ pc() - start, map->deep_copy());
1428   ContinuationEntry::_return_pc_offset = __ pc() - start;
1429   __ post_call_nop();
1430 
1431   __ bind(exit);
1432   ContinuationEntry::_cleanup_offset = __ pc() - start;
1433   continuation_enter_cleanup(masm);
1434   __ leave();
1435   __ ret(lr);
1436 
1437   /// exception handling
1438 
1439   exception_offset = __ pc() - start;
1440   {
1441       __ mov(r19, r0); // save return value contaning the exception oop in callee-saved R19
1442 
1443       continuation_enter_cleanup(masm);
1444 
1445       __ ldr(c_rarg1, Address(rfp, wordSize)); // return address
1446       __ authenticate_return_address(c_rarg1);
1447       __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::exception_handler_for_return_address), rthread, c_rarg1);
1448 
1449       // see OptoRuntime::generate_exception_blob: r0 -- exception oop, r3 -- exception pc
1450 
1451       __ mov(r1, r0); // the exception handler
1452       __ mov(r0, r19); // restore return value contaning the exception oop
1453       __ verify_oop(r0);
1454 
1455       __ leave();
1456       __ mov(r3, lr);
1457       __ br(r1); // the exception handler
1458   }
1459 
1460   address stub = CompiledDirectCall::emit_to_interp_stub(masm, tr_call);
1461   if (stub == nullptr) {
1462     fatal("CodeCache is full at gen_continuation_enter");
1463   }
1464 }
1465 
1466 static void gen_continuation_yield(MacroAssembler* masm,
1467                                    const methodHandle& method,
1468                                    const BasicType* sig_bt,
1469                                    const VMRegPair* regs,
1470                                    OopMapSet* oop_maps,
1471                                    int& frame_complete,
1472                                    int& stack_slots,
1473                                    int& compiled_entry_offset) {
1474     enum layout {
1475       rfp_off1,
1476       rfp_off2,
1477       lr_off,
1478       lr_off2,
1479       framesize // inclusive of return address
1480     };
1481     // assert(is_even(framesize/2), "sp not 16-byte aligned");
1482     stack_slots = framesize /  VMRegImpl::slots_per_word;
1483     assert(stack_slots == 2, "recheck layout");
1484 
1485     address start = __ pc();
1486 
1487     compiled_entry_offset = __ pc() - start;
1488     __ enter();
1489 
1490     __ mov(c_rarg1, sp);
1491 
1492     frame_complete = __ pc() - start;
1493     address the_pc = __ pc();
1494 
1495     __ post_call_nop(); // this must be exactly after the pc value that is pushed into the frame info, we use this nop for fast CodeBlob lookup
1496 
1497     __ mov(c_rarg0, rthread);
1498     __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
1499     __ call_VM_leaf(Continuation::freeze_entry(), 2);
1500     __ reset_last_Java_frame(true);
1501 
1502     Label pinned;
1503 
1504     __ cbnz(r0, pinned);
1505 
1506     // We've succeeded, set sp to the ContinuationEntry
1507     __ ldr(rscratch1, Address(rthread, JavaThread::cont_entry_offset()));
1508     __ mov(sp, rscratch1);
1509     continuation_enter_cleanup(masm);
1510 
1511     __ bind(pinned); // pinned -- return to caller
1512 
1513     // handle pending exception thrown by freeze
1514     __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
1515     Label ok;
1516     __ cbz(rscratch1, ok);
1517     __ leave();
1518     __ lea(rscratch1, RuntimeAddress(StubRoutines::forward_exception_entry()));
1519     __ br(rscratch1);
1520     __ bind(ok);
1521 
1522     __ leave();
1523     __ ret(lr);
1524 
1525     OopMap* map = new OopMap(framesize, 1);
1526     oop_maps->add_gc_map(the_pc - start, map);
1527 }
1528 
1529 void SharedRuntime::continuation_enter_cleanup(MacroAssembler* masm) {
1530   ::continuation_enter_cleanup(masm);
1531 }
1532 
1533 static void gen_special_dispatch(MacroAssembler* masm,
1534                                  const methodHandle& method,
1535                                  const BasicType* sig_bt,
1536                                  const VMRegPair* regs) {
1537   verify_oop_args(masm, method, sig_bt, regs);
1538   vmIntrinsics::ID iid = method->intrinsic_id();
1539 
1540   // Now write the args into the outgoing interpreter space
1541   bool     has_receiver   = false;
1542   Register receiver_reg   = noreg;
1543   int      member_arg_pos = -1;
1544   Register member_reg     = noreg;
1545   int      ref_kind       = MethodHandles::signature_polymorphic_intrinsic_ref_kind(iid);
1546   if (ref_kind != 0) {
1547     member_arg_pos = method->size_of_parameters() - 1;  // trailing MemberName argument
1548     member_reg = r19;  // known to be free at this point
1549     has_receiver = MethodHandles::ref_kind_has_receiver(ref_kind);
1550   } else if (iid == vmIntrinsics::_invokeBasic) {
1551     has_receiver = true;
1552   } else if (iid == vmIntrinsics::_linkToNative) {
1553     member_arg_pos = method->size_of_parameters() - 1;  // trailing NativeEntryPoint argument
1554     member_reg = r19;  // known to be free at this point
1555   } else {
1556     fatal("unexpected intrinsic id %d", vmIntrinsics::as_int(iid));
1557   }
1558 
1559   if (member_reg != noreg) {
1560     // Load the member_arg into register, if necessary.
1561     SharedRuntime::check_member_name_argument_is_last_argument(method, sig_bt, regs);
1562     VMReg r = regs[member_arg_pos].first();
1563     if (r->is_stack()) {
1564       __ ldr(member_reg, Address(sp, r->reg2stack() * VMRegImpl::stack_slot_size));
1565     } else {
1566       // no data motion is needed
1567       member_reg = r->as_Register();
1568     }
1569   }
1570 
1571   if (has_receiver) {
1572     // Make sure the receiver is loaded into a register.
1573     assert(method->size_of_parameters() > 0, "oob");
1574     assert(sig_bt[0] == T_OBJECT, "receiver argument must be an object");
1575     VMReg r = regs[0].first();
1576     assert(r->is_valid(), "bad receiver arg");
1577     if (r->is_stack()) {
1578       // Porting note:  This assumes that compiled calling conventions always
1579       // pass the receiver oop in a register.  If this is not true on some
1580       // platform, pick a temp and load the receiver from stack.
1581       fatal("receiver always in a register");
1582       receiver_reg = r2;  // known to be free at this point
1583       __ ldr(receiver_reg, Address(sp, r->reg2stack() * VMRegImpl::stack_slot_size));
1584     } else {
1585       // no data motion is needed
1586       receiver_reg = r->as_Register();
1587     }
1588   }
1589 
1590   // Figure out which address we are really jumping to:
1591   MethodHandles::generate_method_handle_dispatch(masm, iid,
1592                                                  receiver_reg, member_reg, /*for_compiler_entry:*/ true);
1593 }
1594 
1595 // ---------------------------------------------------------------------------
1596 // Generate a native wrapper for a given method.  The method takes arguments
1597 // in the Java compiled code convention, marshals them to the native
1598 // convention (handlizes oops, etc), transitions to native, makes the call,
1599 // returns to java state (possibly blocking), unhandlizes any result and
1600 // returns.
1601 //
1602 // Critical native functions are a shorthand for the use of
1603 // GetPrimtiveArrayCritical and disallow the use of any other JNI
1604 // functions.  The wrapper is expected to unpack the arguments before
1605 // passing them to the callee. Critical native functions leave the state _in_Java,
1606 // since they block out GC.
1607 // Some other parts of JNI setup are skipped like the tear down of the JNI handle
1608 // block and the check for pending exceptions it's impossible for them
1609 // to be thrown.
1610 //
1611 nmethod* SharedRuntime::generate_native_wrapper(MacroAssembler* masm,
1612                                                 const methodHandle& method,
1613                                                 int compile_id,
1614                                                 BasicType* in_sig_bt,
1615                                                 VMRegPair* in_regs,
1616                                                 BasicType ret_type) {
1617   if (method->is_continuation_native_intrinsic()) {
1618     int exception_offset = -1;
1619     OopMapSet* oop_maps = new OopMapSet();
1620     int frame_complete = -1;
1621     int stack_slots = -1;
1622     int interpreted_entry_offset = -1;
1623     int vep_offset = -1;
1624     if (method->is_continuation_enter_intrinsic()) {
1625       gen_continuation_enter(masm,
1626                              method,
1627                              in_sig_bt,
1628                              in_regs,
1629                              exception_offset,
1630                              oop_maps,
1631                              frame_complete,
1632                              stack_slots,
1633                              interpreted_entry_offset,
1634                              vep_offset);
1635     } else if (method->is_continuation_yield_intrinsic()) {
1636       gen_continuation_yield(masm,
1637                              method,
1638                              in_sig_bt,
1639                              in_regs,
1640                              oop_maps,
1641                              frame_complete,
1642                              stack_slots,
1643                              vep_offset);
1644     } else {
1645       guarantee(false, "Unknown Continuation native intrinsic");
1646     }
1647 
1648 #ifdef ASSERT
1649     if (method->is_continuation_enter_intrinsic()) {
1650       assert(interpreted_entry_offset != -1, "Must be set");
1651       assert(exception_offset != -1,         "Must be set");
1652     } else {
1653       assert(interpreted_entry_offset == -1, "Must be unset");
1654       assert(exception_offset == -1,         "Must be unset");
1655     }
1656     assert(frame_complete != -1,    "Must be set");
1657     assert(stack_slots != -1,       "Must be set");
1658     assert(vep_offset != -1,        "Must be set");
1659 #endif
1660 
1661     __ flush();
1662     nmethod* nm = nmethod::new_native_nmethod(method,
1663                                               compile_id,
1664                                               masm->code(),
1665                                               vep_offset,
1666                                               frame_complete,
1667                                               stack_slots,
1668                                               in_ByteSize(-1),
1669                                               in_ByteSize(-1),
1670                                               oop_maps,
1671                                               exception_offset);
1672     if (nm == nullptr) return nm;
1673     if (method->is_continuation_enter_intrinsic()) {
1674       ContinuationEntry::set_enter_code(nm, interpreted_entry_offset);
1675     } else if (method->is_continuation_yield_intrinsic()) {
1676       _cont_doYield_stub = nm;
1677     } else {
1678       guarantee(false, "Unknown Continuation native intrinsic");
1679     }
1680     return nm;
1681   }
1682 
1683   if (method->is_method_handle_intrinsic()) {
1684     vmIntrinsics::ID iid = method->intrinsic_id();
1685     intptr_t start = (intptr_t)__ pc();
1686     int vep_offset = ((intptr_t)__ pc()) - start;
1687 
1688     // First instruction must be a nop as it may need to be patched on deoptimisation
1689     __ nop();
1690     gen_special_dispatch(masm,
1691                          method,
1692                          in_sig_bt,
1693                          in_regs);
1694     int frame_complete = ((intptr_t)__ pc()) - start;  // not complete, period
1695     __ flush();
1696     int stack_slots = SharedRuntime::out_preserve_stack_slots();  // no out slots at all, actually
1697     return nmethod::new_native_nmethod(method,
1698                                        compile_id,
1699                                        masm->code(),
1700                                        vep_offset,
1701                                        frame_complete,
1702                                        stack_slots / VMRegImpl::slots_per_word,
1703                                        in_ByteSize(-1),
1704                                        in_ByteSize(-1),
1705                                        nullptr);
1706   }
1707   address native_func = method->native_function();
1708   assert(native_func != nullptr, "must have function");
1709 
1710   // An OopMap for lock (and class if static)
1711   OopMapSet *oop_maps = new OopMapSet();
1712   intptr_t start = (intptr_t)__ pc();
1713 
1714   // We have received a description of where all the java arg are located
1715   // on entry to the wrapper. We need to convert these args to where
1716   // the jni function will expect them. To figure out where they go
1717   // we convert the java signature to a C signature by inserting
1718   // the hidden arguments as arg[0] and possibly arg[1] (static method)
1719 
1720   const int total_in_args = method->size_of_parameters();
1721   int total_c_args = total_in_args + (method->is_static() ? 2 : 1);
1722 
1723   BasicType* out_sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_c_args);
1724   VMRegPair* out_regs   = NEW_RESOURCE_ARRAY(VMRegPair, total_c_args);
1725 
1726   int argc = 0;
1727   out_sig_bt[argc++] = T_ADDRESS;
1728   if (method->is_static()) {
1729     out_sig_bt[argc++] = T_OBJECT;
1730   }
1731 
1732   for (int i = 0; i < total_in_args ; i++ ) {
1733     out_sig_bt[argc++] = in_sig_bt[i];
1734   }
1735 
1736   // Now figure out where the args must be stored and how much stack space
1737   // they require.
1738   int out_arg_slots;
1739   out_arg_slots = c_calling_convention_priv(out_sig_bt, out_regs, total_c_args);
1740 
1741   if (out_arg_slots < 0) {
1742     return nullptr;
1743   }
1744 
1745   // Compute framesize for the wrapper.  We need to handlize all oops in
1746   // incoming registers
1747 
1748   // Calculate the total number of stack slots we will need.
1749 
1750   // First count the abi requirement plus all of the outgoing args
1751   int stack_slots = SharedRuntime::out_preserve_stack_slots() + out_arg_slots;
1752 
1753   // Now the space for the inbound oop handle area
1754   int total_save_slots = 8 * VMRegImpl::slots_per_word;  // 8 arguments passed in registers
1755 
1756   int oop_handle_offset = stack_slots;
1757   stack_slots += total_save_slots;
1758 
1759   // Now any space we need for handlizing a klass if static method
1760 
1761   int klass_slot_offset = 0;
1762   int klass_offset = -1;
1763   int lock_slot_offset = 0;
1764   bool is_static = false;
1765 
1766   if (method->is_static()) {
1767     klass_slot_offset = stack_slots;
1768     stack_slots += VMRegImpl::slots_per_word;
1769     klass_offset = klass_slot_offset * VMRegImpl::stack_slot_size;
1770     is_static = true;
1771   }
1772 
1773   // Plus a lock if needed
1774 
1775   if (method->is_synchronized()) {
1776     lock_slot_offset = stack_slots;
1777     stack_slots += VMRegImpl::slots_per_word;
1778   }
1779 
1780   // Now a place (+2) to save return values or temp during shuffling
1781   // + 4 for return address (which we own) and saved rfp
1782   stack_slots += 6;
1783 
1784   // Ok The space we have allocated will look like:
1785   //
1786   //
1787   // FP-> |                     |
1788   //      |---------------------|
1789   //      | 2 slots for moves   |
1790   //      |---------------------|
1791   //      | lock box (if sync)  |
1792   //      |---------------------| <- lock_slot_offset
1793   //      | klass (if static)   |
1794   //      |---------------------| <- klass_slot_offset
1795   //      | oopHandle area      |
1796   //      |---------------------| <- oop_handle_offset (8 java arg registers)
1797   //      | outbound memory     |
1798   //      | based arguments     |
1799   //      |                     |
1800   //      |---------------------|
1801   //      |                     |
1802   // SP-> | out_preserved_slots |
1803   //
1804   //
1805 
1806 
1807   // Now compute actual number of stack words we need rounding to make
1808   // stack properly aligned.
1809   stack_slots = align_up(stack_slots, StackAlignmentInSlots);
1810 
1811   int stack_size = stack_slots * VMRegImpl::stack_slot_size;
1812 
1813   // First thing make an ic check to see if we should even be here
1814 
1815   // We are free to use all registers as temps without saving them and
1816   // restoring them except rfp. rfp is the only callee save register
1817   // as far as the interpreter and the compiler(s) are concerned.
1818 
1819   const Register receiver = j_rarg0;
1820 
1821   Label exception_pending;
1822 
1823   assert_different_registers(receiver, rscratch1);
1824   __ verify_oop(receiver);
1825   __ ic_check(8 /* end_alignment */);
1826 
1827   // Verified entry point must be aligned
1828   int vep_offset = ((intptr_t)__ pc()) - start;
1829 
1830   // If we have to make this method not-entrant we'll overwrite its
1831   // first instruction with a jump.  For this action to be legal we
1832   // must ensure that this first instruction is a B, BL, NOP, BKPT,
1833   // SVC, HVC, or SMC.  Make it a NOP.
1834   __ nop();
1835 
1836   if (VM_Version::supports_fast_class_init_checks() && method->needs_clinit_barrier()) {
1837     Label L_skip_barrier;
1838     __ mov_metadata(rscratch2, method->method_holder()); // InstanceKlass*
1839     __ clinit_barrier(rscratch2, rscratch1, &L_skip_barrier);
1840     __ far_jump(RuntimeAddress(SharedRuntime::get_handle_wrong_method_stub()));
1841 
1842     __ bind(L_skip_barrier);
1843   }
1844 
1845   // Generate stack overflow check
1846   __ bang_stack_with_offset(checked_cast<int>(StackOverflow::stack_shadow_zone_size()));
1847 
1848   // Generate a new frame for the wrapper.
1849   __ enter();
1850   // -2 because return address is already present and so is saved rfp
1851   __ sub(sp, sp, stack_size - 2*wordSize);
1852 
1853   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
1854   bs->nmethod_entry_barrier(masm, nullptr /* slow_path */, nullptr /* continuation */, nullptr /* guard */);
1855 
1856   // Frame is now completed as far as size and linkage.
1857   int frame_complete = ((intptr_t)__ pc()) - start;
1858 
1859   // We use r20 as the oop handle for the receiver/klass
1860   // It is callee save so it survives the call to native
1861 
1862   const Register oop_handle_reg = r20;
1863 
1864   //
1865   // We immediately shuffle the arguments so that any vm call we have to
1866   // make from here on out (sync slow path, jvmti, etc.) we will have
1867   // captured the oops from our caller and have a valid oopMap for
1868   // them.
1869 
1870   // -----------------
1871   // The Grand Shuffle
1872 
1873   // The Java calling convention is either equal (linux) or denser (win64) than the
1874   // c calling convention. However the because of the jni_env argument the c calling
1875   // convention always has at least one more (and two for static) arguments than Java.
1876   // Therefore if we move the args from java -> c backwards then we will never have
1877   // a register->register conflict and we don't have to build a dependency graph
1878   // and figure out how to break any cycles.
1879   //
1880 
1881   // Record esp-based slot for receiver on stack for non-static methods
1882   int receiver_offset = -1;
1883 
1884   // This is a trick. We double the stack slots so we can claim
1885   // the oops in the caller's frame. Since we are sure to have
1886   // more args than the caller doubling is enough to make
1887   // sure we can capture all the incoming oop args from the
1888   // caller.
1889   //
1890   OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1891 
1892   // Mark location of rfp (someday)
1893   // map->set_callee_saved(VMRegImpl::stack2reg( stack_slots - 2), stack_slots * 2, 0, vmreg(rfp));
1894 
1895 
1896   int float_args = 0;
1897   int int_args = 0;
1898 
1899 #ifdef ASSERT
1900   bool reg_destroyed[Register::number_of_registers];
1901   bool freg_destroyed[FloatRegister::number_of_registers];
1902   for ( int r = 0 ; r < Register::number_of_registers ; r++ ) {
1903     reg_destroyed[r] = false;
1904   }
1905   for ( int f = 0 ; f < FloatRegister::number_of_registers ; f++ ) {
1906     freg_destroyed[f] = false;
1907   }
1908 
1909 #endif /* ASSERT */
1910 
1911   // For JNI natives the incoming and outgoing registers are offset upwards.
1912   GrowableArray<int> arg_order(2 * total_in_args);
1913 
1914   for (int i = total_in_args - 1, c_arg = total_c_args - 1; i >= 0; i--, c_arg--) {
1915     arg_order.push(i);
1916     arg_order.push(c_arg);
1917   }
1918 
1919   for (int ai = 0; ai < arg_order.length(); ai += 2) {
1920     int i = arg_order.at(ai);
1921     int c_arg = arg_order.at(ai + 1);
1922     __ block_comment(err_msg("move %d -> %d", i, c_arg));
1923     assert(c_arg != -1 && i != -1, "wrong order");
1924 #ifdef ASSERT
1925     if (in_regs[i].first()->is_Register()) {
1926       assert(!reg_destroyed[in_regs[i].first()->as_Register()->encoding()], "destroyed reg!");
1927     } else if (in_regs[i].first()->is_FloatRegister()) {
1928       assert(!freg_destroyed[in_regs[i].first()->as_FloatRegister()->encoding()], "destroyed reg!");
1929     }
1930     if (out_regs[c_arg].first()->is_Register()) {
1931       reg_destroyed[out_regs[c_arg].first()->as_Register()->encoding()] = true;
1932     } else if (out_regs[c_arg].first()->is_FloatRegister()) {
1933       freg_destroyed[out_regs[c_arg].first()->as_FloatRegister()->encoding()] = true;
1934     }
1935 #endif /* ASSERT */
1936     switch (in_sig_bt[i]) {
1937       case T_ARRAY:
1938       case T_OBJECT:
1939         __ object_move(map, oop_handle_offset, stack_slots, in_regs[i], out_regs[c_arg],
1940                        ((i == 0) && (!is_static)),
1941                        &receiver_offset);
1942         int_args++;
1943         break;
1944       case T_VOID:
1945         break;
1946 
1947       case T_FLOAT:
1948         __ float_move(in_regs[i], out_regs[c_arg]);
1949         float_args++;
1950         break;
1951 
1952       case T_DOUBLE:
1953         assert( i + 1 < total_in_args &&
1954                 in_sig_bt[i + 1] == T_VOID &&
1955                 out_sig_bt[c_arg+1] == T_VOID, "bad arg list");
1956         __ double_move(in_regs[i], out_regs[c_arg]);
1957         float_args++;
1958         break;
1959 
1960       case T_LONG :
1961         __ long_move(in_regs[i], out_regs[c_arg]);
1962         int_args++;
1963         break;
1964 
1965       case T_ADDRESS: assert(false, "found T_ADDRESS in java args");
1966 
1967       default:
1968         __ move32_64(in_regs[i], out_regs[c_arg]);
1969         int_args++;
1970     }
1971   }
1972 
1973   // point c_arg at the first arg that is already loaded in case we
1974   // need to spill before we call out
1975   int c_arg = total_c_args - total_in_args;
1976 
1977   // Pre-load a static method's oop into c_rarg1.
1978   if (method->is_static()) {
1979 
1980     //  load oop into a register
1981     __ movoop(c_rarg1,
1982               JNIHandles::make_local(method->method_holder()->java_mirror()));
1983 
1984     // Now handlize the static class mirror it's known not-null.
1985     __ str(c_rarg1, Address(sp, klass_offset));
1986     map->set_oop(VMRegImpl::stack2reg(klass_slot_offset));
1987 
1988     // Now get the handle
1989     __ lea(c_rarg1, Address(sp, klass_offset));
1990     // and protect the arg if we must spill
1991     c_arg--;
1992   }
1993 
1994   // Change state to native (we save the return address in the thread, since it might not
1995   // be pushed on the stack when we do a stack traversal). It is enough that the pc()
1996   // points into the right code segment. It does not have to be the correct return pc.
1997   // We use the same pc/oopMap repeatedly when we call out.
1998 
1999   Label native_return;
2000   if (method->is_object_wait0()) {
2001     // For convenience we use the pc we want to resume to in case of preemption on Object.wait.
2002     __ set_last_Java_frame(sp, noreg, native_return, rscratch1);
2003   } else {
2004     intptr_t the_pc = (intptr_t) __ pc();
2005     oop_maps->add_gc_map(the_pc - start, map);
2006 
2007     __ set_last_Java_frame(sp, noreg, __ pc(), rscratch1);
2008   }
2009 
2010   Label dtrace_method_entry, dtrace_method_entry_done;
2011   if (DTraceMethodProbes) {
2012     __ b(dtrace_method_entry);
2013     __ bind(dtrace_method_entry_done);
2014   }
2015 
2016   // RedefineClasses() tracing support for obsolete method entry
2017   if (log_is_enabled(Trace, redefine, class, obsolete)) {
2018     // protect the args we've loaded
2019     save_args(masm, total_c_args, c_arg, out_regs);
2020     __ mov_metadata(c_rarg1, method());
2021     __ call_VM_leaf(
2022       CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
2023       rthread, c_rarg1);
2024     restore_args(masm, total_c_args, c_arg, out_regs);
2025   }
2026 
2027   // Lock a synchronized method
2028 
2029   // Register definitions used by locking and unlocking
2030 
2031   const Register swap_reg = r0;
2032   const Register obj_reg  = r19;  // Will contain the oop
2033   const Register lock_reg = r13;  // Address of compiler lock object (BasicLock)
2034   const Register old_hdr  = r13;  // value of old header at unlock time
2035   const Register lock_tmp = r14;  // Temporary used by lightweight_lock/unlock
2036   const Register tmp = lr;
2037 
2038   Label slow_path_lock;
2039   Label lock_done;
2040 
2041   if (method->is_synchronized()) {
2042     // Get the handle (the 2nd argument)
2043     __ mov(oop_handle_reg, c_rarg1);
2044 
2045     // Get address of the box
2046 
2047     __ lea(lock_reg, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
2048 
2049     // Load the oop from the handle
2050     __ ldr(obj_reg, Address(oop_handle_reg, 0));
2051 
2052     __ lightweight_lock(lock_reg, obj_reg, swap_reg, tmp, lock_tmp, slow_path_lock);
2053 
2054     // Slow path will re-enter here
2055     __ bind(lock_done);
2056   }
2057 
2058 
2059   // Finally just about ready to make the JNI call
2060 
2061   // get JNIEnv* which is first argument to native
2062   __ lea(c_rarg0, Address(rthread, in_bytes(JavaThread::jni_environment_offset())));
2063 
2064   // Now set thread in native
2065   __ mov(rscratch1, _thread_in_native);
2066   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
2067   __ stlrw(rscratch1, rscratch2);
2068 
2069   __ rt_call(native_func);
2070 
2071   // Verify or restore cpu control state after JNI call
2072   __ restore_cpu_control_state_after_jni(rscratch1, rscratch2);
2073 
2074   // Unpack native results.
2075   switch (ret_type) {
2076   case T_BOOLEAN: __ c2bool(r0);                     break;
2077   case T_CHAR   : __ ubfx(r0, r0, 0, 16);            break;
2078   case T_BYTE   : __ sbfx(r0, r0, 0, 8);             break;
2079   case T_SHORT  : __ sbfx(r0, r0, 0, 16);            break;
2080   case T_INT    : __ sbfx(r0, r0, 0, 32);            break;
2081   case T_DOUBLE :
2082   case T_FLOAT  :
2083     // Result is in v0 we'll save as needed
2084     break;
2085   case T_ARRAY:                 // Really a handle
2086   case T_OBJECT:                // Really a handle
2087       break; // can't de-handlize until after safepoint check
2088   case T_VOID: break;
2089   case T_LONG: break;
2090   default       : ShouldNotReachHere();
2091   }
2092 
2093   Label safepoint_in_progress, safepoint_in_progress_done;
2094 
2095   // Switch thread to "native transition" state before reading the synchronization state.
2096   // This additional state is necessary because reading and testing the synchronization
2097   // state is not atomic w.r.t. GC, as this scenario demonstrates:
2098   //     Java thread A, in _thread_in_native state, loads _not_synchronized and is preempted.
2099   //     VM thread changes sync state to synchronizing and suspends threads for GC.
2100   //     Thread A is resumed to finish this native method, but doesn't block here since it
2101   //     didn't see any synchronization is progress, and escapes.
2102   __ mov(rscratch1, _thread_in_native_trans);
2103 
2104   __ strw(rscratch1, Address(rthread, JavaThread::thread_state_offset()));
2105 
2106   // Force this write out before the read below
2107   if (!UseSystemMemoryBarrier) {
2108     __ dmb(Assembler::ISH);
2109   }
2110 
2111   __ verify_sve_vector_length();
2112 
2113   // Check for safepoint operation in progress and/or pending suspend requests.
2114   {
2115     // No need for acquire as Java threads always disarm themselves.
2116     __ safepoint_poll(safepoint_in_progress, true /* at_return */, false /* in_nmethod */);
2117     __ ldrw(rscratch1, Address(rthread, JavaThread::suspend_flags_offset()));
2118     __ cbnzw(rscratch1, safepoint_in_progress);
2119     __ bind(safepoint_in_progress_done);
2120   }
2121 
2122   // change thread state
2123   __ mov(rscratch1, _thread_in_Java);
2124   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
2125   __ stlrw(rscratch1, rscratch2);
2126 
2127   if (method->is_object_wait0()) {
2128     // Check preemption for Object.wait()
2129     __ ldr(rscratch1, Address(rthread, JavaThread::preempt_alternate_return_offset()));
2130     __ cbz(rscratch1, native_return);
2131     __ str(zr, Address(rthread, JavaThread::preempt_alternate_return_offset()));
2132     __ br(rscratch1);
2133     __ bind(native_return);
2134 
2135     intptr_t the_pc = (intptr_t) __ pc();
2136     oop_maps->add_gc_map(the_pc - start, map);
2137   }
2138 
2139   Label reguard;
2140   Label reguard_done;
2141   __ ldrb(rscratch1, Address(rthread, JavaThread::stack_guard_state_offset()));
2142   __ cmpw(rscratch1, StackOverflow::stack_guard_yellow_reserved_disabled);
2143   __ br(Assembler::EQ, reguard);
2144   __ bind(reguard_done);
2145 
2146   // native result if any is live
2147 
2148   // Unlock
2149   Label unlock_done;
2150   Label slow_path_unlock;
2151   if (method->is_synchronized()) {
2152 
2153     // Get locked oop from the handle we passed to jni
2154     __ ldr(obj_reg, Address(oop_handle_reg, 0));
2155 
2156     // Must save r0 if if it is live now because cmpxchg must use it
2157     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
2158       save_native_result(masm, ret_type, stack_slots);
2159     }
2160 
2161     __ lightweight_unlock(obj_reg, old_hdr, swap_reg, lock_tmp, slow_path_unlock);
2162 
2163     // slow path re-enters here
2164     __ bind(unlock_done);
2165     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
2166       restore_native_result(masm, ret_type, stack_slots);
2167     }
2168   }
2169 
2170   Label dtrace_method_exit, dtrace_method_exit_done;
2171   if (DTraceMethodProbes) {
2172     __ b(dtrace_method_exit);
2173     __ bind(dtrace_method_exit_done);
2174   }
2175 
2176   __ reset_last_Java_frame(false);
2177 
2178   // Unbox oop result, e.g. JNIHandles::resolve result.
2179   if (is_reference_type(ret_type)) {
2180     __ resolve_jobject(r0, r1, r2);
2181   }
2182 
2183   if (CheckJNICalls) {
2184     // clear_pending_jni_exception_check
2185     __ str(zr, Address(rthread, JavaThread::pending_jni_exception_check_fn_offset()));
2186   }
2187 
2188   // reset handle block
2189   __ ldr(r2, Address(rthread, JavaThread::active_handles_offset()));
2190   __ str(zr, Address(r2, JNIHandleBlock::top_offset()));
2191 
2192   __ leave();
2193 
2194   #if INCLUDE_JFR
2195   // We need to do a poll test after unwind in case the sampler
2196   // managed to sample the native frame after returning to Java.
2197   Label L_return;
2198   __ ldr(rscratch1, Address(rthread, JavaThread::polling_word_offset()));
2199   address poll_test_pc = __ pc();
2200   __ relocate(relocInfo::poll_return_type);
2201   __ tbz(rscratch1, log2i_exact(SafepointMechanism::poll_bit()), L_return);
2202   assert(SharedRuntime::polling_page_return_handler_blob() != nullptr,
2203     "polling page return stub not created yet");
2204   address stub = SharedRuntime::polling_page_return_handler_blob()->entry_point();
2205   __ adr(rscratch1, InternalAddress(poll_test_pc));
2206   __ str(rscratch1, Address(rthread, JavaThread::saved_exception_pc_offset()));
2207   __ far_jump(RuntimeAddress(stub));
2208   __ bind(L_return);
2209 #endif // INCLUDE_JFR
2210 
2211   // Any exception pending?
2212   __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2213   __ cbnz(rscratch1, exception_pending);
2214 
2215   // We're done
2216   __ ret(lr);
2217 
2218   // Unexpected paths are out of line and go here
2219 
2220   // forward the exception
2221   __ bind(exception_pending);
2222 
2223   // and forward the exception
2224   __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2225 
2226   // Slow path locking & unlocking
2227   if (method->is_synchronized()) {
2228 
2229     __ block_comment("Slow path lock {");
2230     __ bind(slow_path_lock);
2231 
2232     // has last_Java_frame setup. No exceptions so do vanilla call not call_VM
2233     // args are (oop obj, BasicLock* lock, JavaThread* thread)
2234 
2235     // protect the args we've loaded
2236     save_args(masm, total_c_args, c_arg, out_regs);
2237 
2238     __ mov(c_rarg0, obj_reg);
2239     __ mov(c_rarg1, lock_reg);
2240     __ mov(c_rarg2, rthread);
2241 
2242     // Not a leaf but we have last_Java_frame setup as we want.
2243     // We don't want to unmount in case of contention since that would complicate preserving
2244     // the arguments that had already been marshalled into the native convention. So we force
2245     // the freeze slow path to find this native wrapper frame (see recurse_freeze_native_frame())
2246     // and pin the vthread. Otherwise the fast path won't find it since we don't walk the stack.
2247     __ push_cont_fastpath();
2248     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_locking_C), 3);
2249     __ pop_cont_fastpath();
2250     restore_args(masm, total_c_args, c_arg, out_regs);
2251 
2252 #ifdef ASSERT
2253     { Label L;
2254       __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2255       __ cbz(rscratch1, L);
2256       __ stop("no pending exception allowed on exit from monitorenter");
2257       __ bind(L);
2258     }
2259 #endif
2260     __ b(lock_done);
2261 
2262     __ block_comment("} Slow path lock");
2263 
2264     __ block_comment("Slow path unlock {");
2265     __ bind(slow_path_unlock);
2266 
2267     // If we haven't already saved the native result we must save it now as xmm registers
2268     // are still exposed.
2269 
2270     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2271       save_native_result(masm, ret_type, stack_slots);
2272     }
2273 
2274     __ mov(c_rarg2, rthread);
2275     __ lea(c_rarg1, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
2276     __ mov(c_rarg0, obj_reg);
2277 
2278     // Save pending exception around call to VM (which contains an EXCEPTION_MARK)
2279     // NOTE that obj_reg == r19 currently
2280     __ ldr(r19, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2281     __ str(zr, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2282 
2283     __ rt_call(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C));
2284 
2285 #ifdef ASSERT
2286     {
2287       Label L;
2288       __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2289       __ cbz(rscratch1, L);
2290       __ stop("no pending exception allowed on exit complete_monitor_unlocking_C");
2291       __ bind(L);
2292     }
2293 #endif /* ASSERT */
2294 
2295     __ str(r19, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2296 
2297     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2298       restore_native_result(masm, ret_type, stack_slots);
2299     }
2300     __ b(unlock_done);
2301 
2302     __ block_comment("} Slow path unlock");
2303 
2304   } // synchronized
2305 
2306   // SLOW PATH Reguard the stack if needed
2307 
2308   __ bind(reguard);
2309   save_native_result(masm, ret_type, stack_slots);
2310   __ rt_call(CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages));
2311   restore_native_result(masm, ret_type, stack_slots);
2312   // and continue
2313   __ b(reguard_done);
2314 
2315   // SLOW PATH safepoint
2316   {
2317     __ block_comment("safepoint {");
2318     __ bind(safepoint_in_progress);
2319 
2320     // Don't use call_VM as it will see a possible pending exception and forward it
2321     // and never return here preventing us from clearing _last_native_pc down below.
2322     //
2323     save_native_result(masm, ret_type, stack_slots);
2324     __ mov(c_rarg0, rthread);
2325 #ifndef PRODUCT
2326   assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
2327 #endif
2328     __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans)));
2329     __ blr(rscratch1);
2330 
2331     // Restore any method result value
2332     restore_native_result(masm, ret_type, stack_slots);
2333 
2334     __ b(safepoint_in_progress_done);
2335     __ block_comment("} safepoint");
2336   }
2337 
2338   // SLOW PATH dtrace support
2339   if (DTraceMethodProbes) {
2340     {
2341       __ block_comment("dtrace entry {");
2342       __ bind(dtrace_method_entry);
2343 
2344       // We have all of the arguments setup at this point. We must not touch any register
2345       // argument registers at this point (what if we save/restore them there are no oop?
2346 
2347       save_args(masm, total_c_args, c_arg, out_regs);
2348       __ mov_metadata(c_rarg1, method());
2349       __ call_VM_leaf(
2350         CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry),
2351         rthread, c_rarg1);
2352       restore_args(masm, total_c_args, c_arg, out_regs);
2353       __ b(dtrace_method_entry_done);
2354       __ block_comment("} dtrace entry");
2355     }
2356 
2357     {
2358       __ block_comment("dtrace exit {");
2359       __ bind(dtrace_method_exit);
2360       save_native_result(masm, ret_type, stack_slots);
2361       __ mov_metadata(c_rarg1, method());
2362       __ call_VM_leaf(
2363         CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit),
2364         rthread, c_rarg1);
2365       restore_native_result(masm, ret_type, stack_slots);
2366       __ b(dtrace_method_exit_done);
2367       __ block_comment("} dtrace exit");
2368     }
2369   }
2370 
2371   __ flush();
2372 
2373   nmethod *nm = nmethod::new_native_nmethod(method,
2374                                             compile_id,
2375                                             masm->code(),
2376                                             vep_offset,
2377                                             frame_complete,
2378                                             stack_slots / VMRegImpl::slots_per_word,
2379                                             (is_static ? in_ByteSize(klass_offset) : in_ByteSize(receiver_offset)),
2380                                             in_ByteSize(lock_slot_offset*VMRegImpl::stack_slot_size),
2381                                             oop_maps);
2382 
2383   return nm;
2384 }
2385 
2386 // this function returns the adjust size (in number of words) to a c2i adapter
2387 // activation for use during deoptimization
2388 int Deoptimization::last_frame_adjust(int callee_parameters, int callee_locals) {
2389   assert(callee_locals >= callee_parameters,
2390           "test and remove; got more parms than locals");
2391   if (callee_locals < callee_parameters)
2392     return 0;                   // No adjustment for negative locals
2393   int diff = (callee_locals - callee_parameters) * Interpreter::stackElementWords;
2394   // diff is counted in stack words
2395   return align_up(diff, 2);
2396 }
2397 
2398 
2399 //------------------------------generate_deopt_blob----------------------------
2400 void SharedRuntime::generate_deopt_blob() {
2401   // Allocate space for the code
2402   ResourceMark rm;
2403   // Setup code generation tools
2404   int pad = 0;
2405 #if INCLUDE_JVMCI
2406   if (EnableJVMCI) {
2407     pad += 512; // Increase the buffer size when compiling for JVMCI
2408   }
2409 #endif
2410   const char* name = SharedRuntime::stub_name(StubId::shared_deopt_id);
2411   CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::SharedBlob, BlobId::shared_deopt_id);
2412   if (blob != nullptr) {
2413     _deopt_blob = blob->as_deoptimization_blob();
2414     return;
2415   }
2416 
2417   CodeBuffer buffer(name, 2048+pad, 1024);
2418   MacroAssembler* masm = new MacroAssembler(&buffer);
2419   int frame_size_in_words;
2420   OopMap* map = nullptr;
2421   OopMapSet *oop_maps = new OopMapSet();
2422   RegisterSaver reg_save(COMPILER2_OR_JVMCI != 0);
2423 
2424   // -------------
2425   // This code enters when returning to a de-optimized nmethod.  A return
2426   // address has been pushed on the stack, and return values are in
2427   // registers.
2428   // If we are doing a normal deopt then we were called from the patched
2429   // nmethod from the point we returned to the nmethod. So the return
2430   // address on the stack is wrong by NativeCall::instruction_size
2431   // We will adjust the value so it looks like we have the original return
2432   // address on the stack (like when we eagerly deoptimized).
2433   // In the case of an exception pending when deoptimizing, we enter
2434   // with a return address on the stack that points after the call we patched
2435   // into the exception handler. We have the following register state from,
2436   // e.g., the forward exception stub (see stubGenerator_x86_64.cpp).
2437   //    r0: exception oop
2438   //    r19: exception handler
2439   //    r3: throwing pc
2440   // So in this case we simply jam r3 into the useless return address and
2441   // the stack looks just like we want.
2442   //
2443   // At this point we need to de-opt.  We save the argument return
2444   // registers.  We call the first C routine, fetch_unroll_info().  This
2445   // routine captures the return values and returns a structure which
2446   // describes the current frame size and the sizes of all replacement frames.
2447   // The current frame is compiled code and may contain many inlined
2448   // functions, each with their own JVM state.  We pop the current frame, then
2449   // push all the new frames.  Then we call the C routine unpack_frames() to
2450   // populate these frames.  Finally unpack_frames() returns us the new target
2451   // address.  Notice that callee-save registers are BLOWN here; they have
2452   // already been captured in the vframeArray at the time the return PC was
2453   // patched.
2454   address start = __ pc();
2455   Label cont;
2456 
2457   // Prolog for non exception case!
2458 
2459   // Save everything in sight.
2460   map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2461 
2462   // Normal deoptimization.  Save exec mode for unpack_frames.
2463   __ movw(rcpool, Deoptimization::Unpack_deopt); // callee-saved
2464   __ b(cont);
2465 
2466   int reexecute_offset = __ pc() - start;
2467 #if INCLUDE_JVMCI && !defined(COMPILER1)
2468   if (UseJVMCICompiler) {
2469     // JVMCI does not use this kind of deoptimization
2470     __ should_not_reach_here();
2471   }
2472 #endif
2473 
2474   // Reexecute case
2475   // return address is the pc describes what bci to do re-execute at
2476 
2477   // No need to update map as each call to save_live_registers will produce identical oopmap
2478   (void) reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2479 
2480   __ movw(rcpool, Deoptimization::Unpack_reexecute); // callee-saved
2481   __ b(cont);
2482 
2483 #if INCLUDE_JVMCI
2484   Label after_fetch_unroll_info_call;
2485   int implicit_exception_uncommon_trap_offset = 0;
2486   int uncommon_trap_offset = 0;
2487 
2488   if (EnableJVMCI) {
2489     implicit_exception_uncommon_trap_offset = __ pc() - start;
2490 
2491     __ ldr(lr, Address(rthread, in_bytes(JavaThread::jvmci_implicit_exception_pc_offset())));
2492     __ str(zr, Address(rthread, in_bytes(JavaThread::jvmci_implicit_exception_pc_offset())));
2493 
2494     uncommon_trap_offset = __ pc() - start;
2495 
2496     // Save everything in sight.
2497     reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2498     // fetch_unroll_info needs to call last_java_frame()
2499     Label retaddr;
2500     __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2501 
2502     __ ldrw(c_rarg1, Address(rthread, in_bytes(JavaThread::pending_deoptimization_offset())));
2503     __ movw(rscratch1, -1);
2504     __ strw(rscratch1, Address(rthread, in_bytes(JavaThread::pending_deoptimization_offset())));
2505 
2506     __ movw(rcpool, (int32_t)Deoptimization::Unpack_reexecute);
2507     __ mov(c_rarg0, rthread);
2508     __ movw(c_rarg2, rcpool); // exec mode
2509     __ lea(rscratch1,
2510            RuntimeAddress(CAST_FROM_FN_PTR(address,
2511                                            Deoptimization::uncommon_trap)));
2512     __ blr(rscratch1);
2513     __ bind(retaddr);
2514     oop_maps->add_gc_map( __ pc()-start, map->deep_copy());
2515 
2516     __ reset_last_Java_frame(false);
2517 
2518     __ b(after_fetch_unroll_info_call);
2519   } // EnableJVMCI
2520 #endif // INCLUDE_JVMCI
2521 
2522   int exception_offset = __ pc() - start;
2523 
2524   // Prolog for exception case
2525 
2526   // all registers are dead at this entry point, except for r0, and
2527   // r3 which contain the exception oop and exception pc
2528   // respectively.  Set them in TLS and fall thru to the
2529   // unpack_with_exception_in_tls entry point.
2530 
2531   __ str(r3, Address(rthread, JavaThread::exception_pc_offset()));
2532   __ str(r0, Address(rthread, JavaThread::exception_oop_offset()));
2533 
2534   int exception_in_tls_offset = __ pc() - start;
2535 
2536   // new implementation because exception oop is now passed in JavaThread
2537 
2538   // Prolog for exception case
2539   // All registers must be preserved because they might be used by LinearScan
2540   // Exceptiop oop and throwing PC are passed in JavaThread
2541   // tos: stack at point of call to method that threw the exception (i.e. only
2542   // args are on the stack, no return address)
2543 
2544   // The return address pushed by save_live_registers will be patched
2545   // later with the throwing pc. The correct value is not available
2546   // now because loading it from memory would destroy registers.
2547 
2548   // NB: The SP at this point must be the SP of the method that is
2549   // being deoptimized.  Deoptimization assumes that the frame created
2550   // here by save_live_registers is immediately below the method's SP.
2551   // This is a somewhat fragile mechanism.
2552 
2553   // Save everything in sight.
2554   map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2555 
2556   // Now it is safe to overwrite any register
2557 
2558   // Deopt during an exception.  Save exec mode for unpack_frames.
2559   __ mov(rcpool, Deoptimization::Unpack_exception); // callee-saved
2560 
2561   // load throwing pc from JavaThread and patch it as the return address
2562   // of the current frame. Then clear the field in JavaThread
2563   __ ldr(r3, Address(rthread, JavaThread::exception_pc_offset()));
2564   __ protect_return_address(r3);
2565   __ str(r3, Address(rfp, wordSize));
2566   __ str(zr, Address(rthread, JavaThread::exception_pc_offset()));
2567 
2568 #ifdef ASSERT
2569   // verify that there is really an exception oop in JavaThread
2570   __ ldr(r0, Address(rthread, JavaThread::exception_oop_offset()));
2571   __ verify_oop(r0);
2572 
2573   // verify that there is no pending exception
2574   Label no_pending_exception;
2575   __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
2576   __ cbz(rscratch1, no_pending_exception);
2577   __ stop("must not have pending exception here");
2578   __ bind(no_pending_exception);
2579 #endif
2580 
2581   __ bind(cont);
2582 
2583   // Call C code.  Need thread and this frame, but NOT official VM entry
2584   // crud.  We cannot block on this call, no GC can happen.
2585   //
2586   // UnrollBlock* fetch_unroll_info(JavaThread* thread)
2587 
2588   // fetch_unroll_info needs to call last_java_frame().
2589 
2590   Label retaddr;
2591   __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2592 #ifdef ASSERT
2593   { Label L;
2594     __ ldr(rscratch1, Address(rthread, JavaThread::last_Java_fp_offset()));
2595     __ cbz(rscratch1, L);
2596     __ stop("SharedRuntime::generate_deopt_blob: last_Java_fp not cleared");
2597     __ bind(L);
2598   }
2599 #endif // ASSERT
2600   __ mov(c_rarg0, rthread);
2601   __ mov(c_rarg1, rcpool);
2602   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::fetch_unroll_info)));
2603   __ blr(rscratch1);
2604   __ bind(retaddr);
2605 
2606   // Need to have an oopmap that tells fetch_unroll_info where to
2607   // find any register it might need.
2608   oop_maps->add_gc_map(__ pc() - start, map);
2609 
2610   __ reset_last_Java_frame(false);
2611 
2612 #if INCLUDE_JVMCI
2613   if (EnableJVMCI) {
2614     __ bind(after_fetch_unroll_info_call);
2615   }
2616 #endif
2617 
2618   // Load UnrollBlock* into r5
2619   __ mov(r5, r0);
2620 
2621   __ ldrw(rcpool, Address(r5, Deoptimization::UnrollBlock::unpack_kind_offset()));
2622    Label noException;
2623   __ cmpw(rcpool, Deoptimization::Unpack_exception);   // Was exception pending?
2624   __ br(Assembler::NE, noException);
2625   __ ldr(r0, Address(rthread, JavaThread::exception_oop_offset()));
2626   // QQQ this is useless it was null above
2627   __ ldr(r3, Address(rthread, JavaThread::exception_pc_offset()));
2628   __ str(zr, Address(rthread, JavaThread::exception_oop_offset()));
2629   __ str(zr, Address(rthread, JavaThread::exception_pc_offset()));
2630 
2631   __ verify_oop(r0);
2632 
2633   // Overwrite the result registers with the exception results.
2634   __ str(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2635   // I think this is useless
2636   // __ str(r3, Address(sp, RegisterSaver::r3_offset_in_bytes()));
2637 
2638   __ bind(noException);
2639 
2640   // Only register save data is on the stack.
2641   // Now restore the result registers.  Everything else is either dead
2642   // or captured in the vframeArray.
2643 
2644   // Restore fp result register
2645   __ ldrd(v0, Address(sp, reg_save.v0_offset_in_bytes()));
2646   // Restore integer result register
2647   __ ldr(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2648 
2649   // Pop all of the register save area off the stack
2650   __ add(sp, sp, frame_size_in_words * wordSize);
2651 
2652   // All of the register save area has been popped of the stack. Only the
2653   // return address remains.
2654 
2655   // Pop all the frames we must move/replace.
2656   //
2657   // Frame picture (youngest to oldest)
2658   // 1: self-frame (no frame link)
2659   // 2: deopting frame  (no frame link)
2660   // 3: caller of deopting frame (could be compiled/interpreted).
2661   //
2662   // Note: by leaving the return address of self-frame on the stack
2663   // and using the size of frame 2 to adjust the stack
2664   // when we are done the return to frame 3 will still be on the stack.
2665 
2666   // Pop deoptimized frame
2667   __ ldrw(r2, Address(r5, Deoptimization::UnrollBlock::size_of_deoptimized_frame_offset()));
2668   __ sub(r2, r2, 2 * wordSize);
2669   __ add(sp, sp, r2);
2670   __ ldp(rfp, zr, __ post(sp, 2 * wordSize));
2671 
2672 #ifdef ASSERT
2673   // Compilers generate code that bang the stack by as much as the
2674   // interpreter would need. So this stack banging should never
2675   // trigger a fault. Verify that it does not on non product builds.
2676   __ ldrw(r19, Address(r5, Deoptimization::UnrollBlock::total_frame_sizes_offset()));
2677   __ bang_stack_size(r19, r2);
2678 #endif
2679   // Load address of array of frame pcs into r2
2680   __ ldr(r2, Address(r5, Deoptimization::UnrollBlock::frame_pcs_offset()));
2681 
2682   // Trash the old pc
2683   // __ addptr(sp, wordSize);  FIXME ????
2684 
2685   // Load address of array of frame sizes into r4
2686   __ ldr(r4, Address(r5, Deoptimization::UnrollBlock::frame_sizes_offset()));
2687 
2688   // Load counter into r3
2689   __ ldrw(r3, Address(r5, Deoptimization::UnrollBlock::number_of_frames_offset()));
2690 
2691   // Now adjust the caller's stack to make up for the extra locals
2692   // but record the original sp so that we can save it in the skeletal interpreter
2693   // frame and the stack walking of interpreter_sender will get the unextended sp
2694   // value and not the "real" sp value.
2695 
2696   const Register sender_sp = r6;
2697 
2698   __ mov(sender_sp, sp);
2699   __ ldrw(r19, Address(r5,
2700                        Deoptimization::UnrollBlock::
2701                        caller_adjustment_offset()));
2702   __ sub(sp, sp, r19);
2703 
2704   // Push interpreter frames in a loop
2705   __ mov(rscratch1, (uint64_t)0xDEADDEAD);        // Make a recognizable pattern
2706   __ mov(rscratch2, rscratch1);
2707   Label loop;
2708   __ bind(loop);
2709   __ ldr(r19, Address(__ post(r4, wordSize)));          // Load frame size
2710   __ sub(r19, r19, 2*wordSize);           // We'll push pc and fp by hand
2711   __ ldr(lr, Address(__ post(r2, wordSize)));  // Load pc
2712   __ enter();                           // Save old & set new fp
2713   __ sub(sp, sp, r19);                  // Prolog
2714   // This value is corrected by layout_activation_impl
2715   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
2716   __ str(sender_sp, Address(rfp, frame::interpreter_frame_sender_sp_offset * wordSize)); // Make it walkable
2717   __ mov(sender_sp, sp);               // Pass sender_sp to next frame
2718   __ sub(r3, r3, 1);                   // Decrement counter
2719   __ cbnz(r3, loop);
2720 
2721     // Re-push self-frame
2722   __ ldr(lr, Address(r2));
2723   __ enter();
2724 
2725   // Allocate a full sized register save area.  We subtract 2 because
2726   // enter() just pushed 2 words
2727   __ sub(sp, sp, (frame_size_in_words - 2) * wordSize);
2728 
2729   // Restore frame locals after moving the frame
2730   __ strd(v0, Address(sp, reg_save.v0_offset_in_bytes()));
2731   __ str(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2732 
2733   // Call C code.  Need thread but NOT official VM entry
2734   // crud.  We cannot block on this call, no GC can happen.  Call should
2735   // restore return values to their stack-slots with the new SP.
2736   //
2737   // void Deoptimization::unpack_frames(JavaThread* thread, int exec_mode)
2738 
2739   // Use rfp because the frames look interpreted now
2740   // Don't need the precise return PC here, just precise enough to point into this code blob.
2741   address the_pc = __ pc();
2742   __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
2743 
2744   __ mov(c_rarg0, rthread);
2745   __ movw(c_rarg1, rcpool); // second arg: exec_mode
2746   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2747   __ blr(rscratch1);
2748 
2749   // Set an oopmap for the call site
2750   // Use the same PC we used for the last java frame
2751   oop_maps->add_gc_map(the_pc - start,
2752                        new OopMap( frame_size_in_words, 0 ));
2753 
2754   // Clear fp AND pc
2755   __ reset_last_Java_frame(true);
2756 
2757   // Collect return values
2758   __ ldrd(v0, Address(sp, reg_save.v0_offset_in_bytes()));
2759   __ ldr(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2760   // I think this is useless (throwing pc?)
2761   // __ ldr(r3, Address(sp, RegisterSaver::r3_offset_in_bytes()));
2762 
2763   // Pop self-frame.
2764   __ leave();                           // Epilog
2765 
2766   // Jump to interpreter
2767   __ ret(lr);
2768 
2769   // Make sure all code is generated
2770   masm->flush();
2771 
2772   _deopt_blob = DeoptimizationBlob::create(&buffer, oop_maps, 0, exception_offset, reexecute_offset, frame_size_in_words);
2773   _deopt_blob->set_unpack_with_exception_in_tls_offset(exception_in_tls_offset);
2774 #if INCLUDE_JVMCI
2775   if (EnableJVMCI) {
2776     _deopt_blob->set_uncommon_trap_offset(uncommon_trap_offset);
2777     _deopt_blob->set_implicit_exception_uncommon_trap_offset(implicit_exception_uncommon_trap_offset);
2778   }
2779 #endif
2780 
2781   AOTCodeCache::store_code_blob(*_deopt_blob, AOTCodeEntry::SharedBlob, BlobId::shared_deopt_id);
2782 }
2783 
2784 // Number of stack slots between incoming argument block and the start of
2785 // a new frame.  The PROLOG must add this many slots to the stack.  The
2786 // EPILOG must remove this many slots. aarch64 needs two slots for
2787 // return address and fp.
2788 // TODO think this is correct but check
2789 uint SharedRuntime::in_preserve_stack_slots() {
2790   return 4;
2791 }
2792 
2793 uint SharedRuntime::out_preserve_stack_slots() {
2794   return 0;
2795 }
2796 
2797 
2798 VMReg SharedRuntime::thread_register() {
2799   return rthread->as_VMReg();
2800 }
2801 
2802 //------------------------------generate_handler_blob------
2803 //
2804 // Generate a special Compile2Runtime blob that saves all registers,
2805 // and setup oopmap.
2806 //
2807 SafepointBlob* SharedRuntime::generate_handler_blob(StubId id, address call_ptr) {
2808   assert(is_polling_page_id(id), "expected a polling page stub id");
2809 
2810   // Allocate space for the code.  Setup code generation tools.
2811   const char* name = SharedRuntime::stub_name(id);
2812   CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::SharedBlob, StubInfo::blob(id));
2813   if (blob != nullptr) {
2814     return blob->as_safepoint_blob();
2815   }
2816 
2817   ResourceMark rm;
2818   OopMapSet *oop_maps = new OopMapSet();
2819   OopMap* map;
2820   CodeBuffer buffer(name, 2048, 1024);
2821   MacroAssembler* masm = new MacroAssembler(&buffer);
2822 
2823   address start   = __ pc();
2824   address call_pc = nullptr;
2825   int frame_size_in_words;
2826   bool cause_return = (id == StubId::shared_polling_page_return_handler_id);
2827   RegisterSaver reg_save(id == StubId::shared_polling_page_vectors_safepoint_handler_id /* save_vectors */);
2828 
2829   // When the signal occurred, the LR was either signed and stored on the stack (in which
2830   // case it will be restored from the stack before being used) or unsigned and not stored
2831   // on the stack. Stipping ensures we get the right value.
2832   __ strip_return_address();
2833 
2834   // Save Integer and Float registers.
2835   map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2836 
2837   // The following is basically a call_VM.  However, we need the precise
2838   // address of the call in order to generate an oopmap. Hence, we do all the
2839   // work ourselves.
2840 
2841   Label retaddr;
2842   __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2843 
2844   // The return address must always be correct so that frame constructor never
2845   // sees an invalid pc.
2846 
2847   if (!cause_return) {
2848     // overwrite the return address pushed by save_live_registers
2849     // Additionally, r20 is a callee-saved register so we can look at
2850     // it later to determine if someone changed the return address for
2851     // us!
2852     __ ldr(r20, Address(rthread, JavaThread::saved_exception_pc_offset()));
2853     __ protect_return_address(r20);
2854     __ str(r20, Address(rfp, wordSize));
2855   }
2856 
2857   // Do the call
2858   __ mov(c_rarg0, rthread);
2859   __ lea(rscratch1, RuntimeAddress(call_ptr));
2860   __ blr(rscratch1);
2861   __ bind(retaddr);
2862 
2863   // Set an oopmap for the call site.  This oopmap will map all
2864   // oop-registers and debug-info registers as callee-saved.  This
2865   // will allow deoptimization at this safepoint to find all possible
2866   // debug-info recordings, as well as let GC find all oops.
2867 
2868   oop_maps->add_gc_map( __ pc() - start, map);
2869 
2870   Label noException;
2871 
2872   __ reset_last_Java_frame(false);
2873 
2874   __ membar(Assembler::LoadLoad | Assembler::LoadStore);
2875 
2876   __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
2877   __ cbz(rscratch1, noException);
2878 
2879   // Exception pending
2880 
2881   reg_save.restore_live_registers(masm);
2882 
2883   __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2884 
2885   // No exception case
2886   __ bind(noException);
2887 
2888   Label no_adjust, bail;
2889   if (!cause_return) {
2890     // If our stashed return pc was modified by the runtime we avoid touching it
2891     __ ldr(rscratch1, Address(rfp, wordSize));
2892     __ cmp(r20, rscratch1);
2893     __ br(Assembler::NE, no_adjust);
2894     __ authenticate_return_address(r20);
2895 
2896 #ifdef ASSERT
2897     // Verify the correct encoding of the poll we're about to skip.
2898     // See NativeInstruction::is_ldrw_to_zr()
2899     __ ldrw(rscratch1, Address(r20));
2900     __ ubfx(rscratch2, rscratch1, 22, 10);
2901     __ cmpw(rscratch2, 0b1011100101);
2902     __ br(Assembler::NE, bail);
2903     __ ubfx(rscratch2, rscratch1, 0, 5);
2904     __ cmpw(rscratch2, 0b11111);
2905     __ br(Assembler::NE, bail);
2906 #endif
2907     // Adjust return pc forward to step over the safepoint poll instruction
2908     __ add(r20, r20, NativeInstruction::instruction_size);
2909     __ protect_return_address(r20);
2910     __ str(r20, Address(rfp, wordSize));
2911   }
2912 
2913   __ bind(no_adjust);
2914   // Normal exit, restore registers and exit.
2915   reg_save.restore_live_registers(masm);
2916 
2917   __ ret(lr);
2918 
2919 #ifdef ASSERT
2920   __ bind(bail);
2921   __ stop("Attempting to adjust pc to skip safepoint poll but the return point is not what we expected");
2922 #endif
2923 
2924   // Make sure all code is generated
2925   masm->flush();
2926 
2927   // Fill-out other meta info
2928   SafepointBlob* sp_blob = SafepointBlob::create(&buffer, oop_maps, frame_size_in_words);
2929 
2930   AOTCodeCache::store_code_blob(*sp_blob, AOTCodeEntry::SharedBlob, StubInfo::blob(id));
2931   return sp_blob;
2932 }
2933 
2934 //
2935 // generate_resolve_blob - call resolution (static/virtual/opt-virtual/ic-miss
2936 //
2937 // Generate a stub that calls into vm to find out the proper destination
2938 // of a java call. All the argument registers are live at this point
2939 // but since this is generic code we don't know what they are and the caller
2940 // must do any gc of the args.
2941 //
2942 RuntimeStub* SharedRuntime::generate_resolve_blob(StubId id, address destination) {
2943   assert (StubRoutines::forward_exception_entry() != nullptr, "must be generated before");
2944   assert(is_resolve_id(id), "expected a resolve stub id");
2945 
2946   const char* name = SharedRuntime::stub_name(id);
2947   CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::SharedBlob, StubInfo::blob(id));
2948   if (blob != nullptr) {
2949     return blob->as_runtime_stub();
2950   }
2951 
2952   // allocate space for the code
2953   ResourceMark rm;
2954   CodeBuffer buffer(name, 1000, 512);
2955   MacroAssembler* masm                = new MacroAssembler(&buffer);
2956 
2957   int frame_size_in_words;
2958   RegisterSaver reg_save(false /* save_vectors */);
2959 
2960   OopMapSet *oop_maps = new OopMapSet();
2961   OopMap* map = nullptr;
2962 
2963   int start = __ offset();
2964 
2965   map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2966 
2967   int frame_complete = __ offset();
2968 
2969   {
2970     Label retaddr;
2971     __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2972 
2973     __ mov(c_rarg0, rthread);
2974     __ lea(rscratch1, RuntimeAddress(destination));
2975 
2976     __ blr(rscratch1);
2977     __ bind(retaddr);
2978   }
2979 
2980   // Set an oopmap for the call site.
2981   // We need this not only for callee-saved registers, but also for volatile
2982   // registers that the compiler might be keeping live across a safepoint.
2983 
2984   oop_maps->add_gc_map( __ offset() - start, map);
2985 
2986   // r0 contains the address we are going to jump to assuming no exception got installed
2987 
2988   // clear last_Java_sp
2989   __ reset_last_Java_frame(false);
2990   // check for pending exceptions
2991   Label pending;
2992   __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
2993   __ cbnz(rscratch1, pending);
2994 
2995   // get the returned Method*
2996   __ get_vm_result_metadata(rmethod, rthread);
2997   __ str(rmethod, Address(sp, reg_save.reg_offset_in_bytes(rmethod)));
2998 
2999   // r0 is where we want to jump, overwrite rscratch1 which is saved and scratch
3000   __ str(r0, Address(sp, reg_save.rscratch1_offset_in_bytes()));
3001   reg_save.restore_live_registers(masm);
3002 
3003   // We are back to the original state on entry and ready to go.
3004 
3005   __ br(rscratch1);
3006 
3007   // Pending exception after the safepoint
3008 
3009   __ bind(pending);
3010 
3011   reg_save.restore_live_registers(masm);
3012 
3013   // exception pending => remove activation and forward to exception handler
3014 
3015   __ str(zr, Address(rthread, JavaThread::vm_result_oop_offset()));
3016 
3017   __ ldr(r0, Address(rthread, Thread::pending_exception_offset()));
3018   __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3019 
3020   // -------------
3021   // make sure all code is generated
3022   masm->flush();
3023 
3024   // return the  blob
3025   // frame_size_words or bytes??
3026   RuntimeStub* rs_blob = RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, frame_size_in_words, oop_maps, true);
3027 
3028   AOTCodeCache::store_code_blob(*rs_blob, AOTCodeEntry::SharedBlob, StubInfo::blob(id));
3029   return rs_blob;
3030 }
3031 
3032 BufferedInlineTypeBlob* SharedRuntime::generate_buffered_inline_type_adapter(const InlineKlass* vk) {
3033   BufferBlob* buf = BufferBlob::create("inline types pack/unpack", 16 * K);
3034   if (buf == nullptr) {
3035     return nullptr;
3036   }
3037   CodeBuffer buffer(buf);
3038   short buffer_locs[20];
3039   buffer.insts()->initialize_shared_locs((relocInfo*)buffer_locs,
3040                                          sizeof(buffer_locs)/sizeof(relocInfo));
3041 
3042   MacroAssembler _masm(&buffer);
3043   MacroAssembler* masm = &_masm;
3044 
3045   const Array<SigEntry>* sig_vk = vk->extended_sig();
3046   const Array<VMRegPair>* regs = vk->return_regs();
3047 
3048   int pack_fields_jobject_off = __ offset();
3049   // Resolve pre-allocated buffer from JNI handle.
3050   // We cannot do this in generate_call_stub() because it requires GC code to be initialized.
3051   Register Rresult = r14;  // See StubGenerator::generate_call_stub().
3052   __ ldr(r0, Address(Rresult));
3053   __ resolve_jobject(r0 /* value */,
3054                      rthread /* thread */,
3055                      r12 /* tmp */);
3056   __ str(r0, Address(Rresult));
3057 
3058   int pack_fields_off = __ offset();
3059 
3060   int j = 1;
3061   for (int i = 0; i < sig_vk->length(); i++) {
3062     BasicType bt = sig_vk->at(i)._bt;
3063     if (bt == T_METADATA) {
3064       continue;
3065     }
3066     if (bt == T_VOID) {
3067       if (sig_vk->at(i-1)._bt == T_LONG ||
3068           sig_vk->at(i-1)._bt == T_DOUBLE) {
3069         j++;
3070       }
3071       continue;
3072     }
3073     int off = sig_vk->at(i)._offset;
3074     VMRegPair pair = regs->at(j);
3075     VMReg r_1 = pair.first();
3076     VMReg r_2 = pair.second();
3077     Address to(r0, off);
3078     if (bt == T_FLOAT) {
3079       __ strs(r_1->as_FloatRegister(), to);
3080     } else if (bt == T_DOUBLE) {
3081       __ strd(r_1->as_FloatRegister(), to);
3082     } else {
3083       Register val = r_1->as_Register();
3084       assert_different_registers(to.base(), val, r15, r16, r17);
3085       if (is_reference_type(bt)) {
3086         __ store_heap_oop(to, val, r15, r16, r17, IN_HEAP | ACCESS_WRITE | IS_DEST_UNINITIALIZED);
3087       } else {
3088         __ store_sized_value(to, r_1->as_Register(), type2aelembytes(bt));
3089       }
3090     }
3091     j++;
3092   }
3093   assert(j == regs->length(), "missed a field?");
3094   if (vk->has_nullable_atomic_layout()) {
3095     // Zero the null marker (setting it to 1 would be better but would require an additional register)
3096     __ strb(zr, Address(r0, vk->null_marker_offset()));
3097   }
3098   __ ret(lr);
3099 
3100   int unpack_fields_off = __ offset();
3101 
3102   Label skip;
3103   Label not_null;
3104   __ cbnz(r0, not_null);
3105 
3106   // Return value is null. Zero oop registers to make the GC happy.
3107   j = 1;
3108   for (int i = 0; i < sig_vk->length(); i++) {
3109     BasicType bt = sig_vk->at(i)._bt;
3110     if (bt == T_METADATA) {
3111       continue;
3112     }
3113     if (bt == T_VOID) {
3114       if (sig_vk->at(i-1)._bt == T_LONG ||
3115           sig_vk->at(i-1)._bt == T_DOUBLE) {
3116         j++;
3117       }
3118       continue;
3119     }
3120     if (bt == T_OBJECT || bt == T_ARRAY) {
3121       VMRegPair pair = regs->at(j);
3122       VMReg r_1 = pair.first();
3123       __ mov(r_1->as_Register(), zr);
3124     }
3125     j++;
3126   }
3127   __ b(skip);
3128   __ bind(not_null);
3129 
3130   j = 1;
3131   for (int i = 0; i < sig_vk->length(); i++) {
3132     BasicType bt = sig_vk->at(i)._bt;
3133     if (bt == T_METADATA) {
3134       continue;
3135     }
3136     if (bt == T_VOID) {
3137       if (sig_vk->at(i-1)._bt == T_LONG ||
3138           sig_vk->at(i-1)._bt == T_DOUBLE) {
3139         j++;
3140       }
3141       continue;
3142     }
3143     int off = sig_vk->at(i)._offset;
3144     assert(off > 0, "offset in object should be positive");
3145     VMRegPair pair = regs->at(j);
3146     VMReg r_1 = pair.first();
3147     VMReg r_2 = pair.second();
3148     Address from(r0, off);
3149     if (bt == T_FLOAT) {
3150       __ ldrs(r_1->as_FloatRegister(), from);
3151     } else if (bt == T_DOUBLE) {
3152       __ ldrd(r_1->as_FloatRegister(), from);
3153     } else if (bt == T_OBJECT || bt == T_ARRAY) {
3154       assert_different_registers(r0, r_1->as_Register());
3155       __ load_heap_oop(r_1->as_Register(), from, rscratch1, rscratch2);
3156     } else {
3157       assert(is_java_primitive(bt), "unexpected basic type");
3158       assert_different_registers(r0, r_1->as_Register());
3159       size_t size_in_bytes = type2aelembytes(bt);
3160       __ load_sized_value(r_1->as_Register(), from, size_in_bytes, bt != T_CHAR && bt != T_BOOLEAN);
3161     }
3162     j++;
3163   }
3164   assert(j == regs->length(), "missed a field?");
3165 
3166   __ bind(skip);
3167 
3168   __ ret(lr);
3169 
3170   __ flush();
3171 
3172   return BufferedInlineTypeBlob::create(&buffer, pack_fields_off, pack_fields_jobject_off, unpack_fields_off);
3173 }
3174 
3175 // Continuation point for throwing of implicit exceptions that are
3176 // not handled in the current activation. Fabricates an exception
3177 // oop and initiates normal exception dispatching in this
3178 // frame. Since we need to preserve callee-saved values (currently
3179 // only for C2, but done for C1 as well) we need a callee-saved oop
3180 // map and therefore have to make these stubs into RuntimeStubs
3181 // rather than BufferBlobs.  If the compiler needs all registers to
3182 // be preserved between the fault point and the exception handler
3183 // then it must assume responsibility for that in
3184 // AbstractCompiler::continuation_for_implicit_null_exception or
3185 // continuation_for_implicit_division_by_zero_exception. All other
3186 // implicit exceptions (e.g., NullPointerException or
3187 // AbstractMethodError on entry) are either at call sites or
3188 // otherwise assume that stack unwinding will be initiated, so
3189 // caller saved registers were assumed volatile in the compiler.
3190 
3191 RuntimeStub* SharedRuntime::generate_throw_exception(StubId id, address runtime_entry) {
3192   assert(is_throw_id(id), "expected a throw stub id");
3193 
3194   const char* name = SharedRuntime::stub_name(id);
3195 
3196   // Information about frame layout at time of blocking runtime call.
3197   // Note that we only have to preserve callee-saved registers since
3198   // the compilers are responsible for supplying a continuation point
3199   // if they expect all registers to be preserved.
3200   // n.b. aarch64 asserts that frame::arg_reg_save_area_bytes == 0
3201   enum layout {
3202     rfp_off = 0,
3203     rfp_off2,
3204     return_off,
3205     return_off2,
3206     framesize // inclusive of return address
3207   };
3208 
3209   int insts_size = 512;
3210   int locs_size  = 64;
3211 
3212   const char* timer_msg = "SharedRuntime generate_throw_exception";
3213   TraceTime timer(timer_msg, TRACETIME_LOG(Info, startuptime));
3214 
3215   CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::SharedBlob, StubInfo::blob(id));
3216   if (blob != nullptr) {
3217     return blob->as_runtime_stub();
3218   }
3219 
3220   ResourceMark rm;
3221   CodeBuffer code(name, insts_size, locs_size);
3222   OopMapSet* oop_maps  = new OopMapSet();
3223   MacroAssembler* masm = new MacroAssembler(&code);
3224 
3225   address start = __ pc();
3226 
3227   // This is an inlined and slightly modified version of call_VM
3228   // which has the ability to fetch the return PC out of
3229   // thread-local storage and also sets up last_Java_sp slightly
3230   // differently than the real call_VM
3231 
3232   __ enter(); // Save FP and LR before call
3233 
3234   assert(is_even(framesize/2), "sp not 16-byte aligned");
3235 
3236   // lr and fp are already in place
3237   __ sub(sp, rfp, ((uint64_t)framesize-4) << LogBytesPerInt); // prolog
3238 
3239   int frame_complete = __ pc() - start;
3240 
3241   // Set up last_Java_sp and last_Java_fp
3242   address the_pc = __ pc();
3243   __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
3244 
3245   __ mov(c_rarg0, rthread);
3246   BLOCK_COMMENT("call runtime_entry");
3247   __ lea(rscratch1, RuntimeAddress(runtime_entry));
3248   __ blr(rscratch1);
3249 
3250   // Generate oop map
3251   OopMap* map = new OopMap(framesize, 0);
3252 
3253   oop_maps->add_gc_map(the_pc - start, map);
3254 
3255   __ reset_last_Java_frame(true);
3256 
3257   // Reinitialize the ptrue predicate register, in case the external runtime
3258   // call clobbers ptrue reg, as we may return to SVE compiled code.
3259   __ reinitialize_ptrue();
3260 
3261   __ leave();
3262 
3263   // check for pending exceptions
3264 #ifdef ASSERT
3265   Label L;
3266   __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
3267   __ cbnz(rscratch1, L);
3268   __ should_not_reach_here();
3269   __ bind(L);
3270 #endif // ASSERT
3271   __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3272 
3273   // codeBlob framesize is in words (not VMRegImpl::slot_size)
3274   RuntimeStub* stub =
3275     RuntimeStub::new_runtime_stub(name,
3276                                   &code,
3277                                   frame_complete,
3278                                   (framesize >> (LogBytesPerWord - LogBytesPerInt)),
3279                                   oop_maps, false);
3280   AOTCodeCache::store_code_blob(*stub, AOTCodeEntry::SharedBlob, StubInfo::blob(id));
3281 
3282   return stub;
3283 }
3284 
3285 #if INCLUDE_JFR
3286 
3287 static void jfr_prologue(address the_pc, MacroAssembler* masm, Register thread) {
3288   __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
3289   __ mov(c_rarg0, thread);
3290 }
3291 
3292 // The handle is dereferenced through a load barrier.
3293 static void jfr_epilogue(MacroAssembler* masm) {
3294   __ reset_last_Java_frame(true);
3295 }
3296 
3297 // For c2: c_rarg0 is junk, call to runtime to write a checkpoint.
3298 // It returns a jobject handle to the event writer.
3299 // The handle is dereferenced and the return value is the event writer oop.
3300 RuntimeStub* SharedRuntime::generate_jfr_write_checkpoint() {
3301   enum layout {
3302     rbp_off,
3303     rbpH_off,
3304     return_off,
3305     return_off2,
3306     framesize // inclusive of return address
3307   };
3308 
3309   int insts_size = 1024;
3310   int locs_size = 64;
3311   const char* name = SharedRuntime::stub_name(StubId::shared_jfr_write_checkpoint_id);
3312   CodeBuffer code(name, insts_size, locs_size);
3313   OopMapSet* oop_maps = new OopMapSet();
3314   MacroAssembler* masm = new MacroAssembler(&code);
3315 
3316   address start = __ pc();
3317   __ enter();
3318   int frame_complete = __ pc() - start;
3319   address the_pc = __ pc();
3320   jfr_prologue(the_pc, masm, rthread);
3321   __ call_VM_leaf(CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::write_checkpoint), 1);
3322   jfr_epilogue(masm);
3323   __ resolve_global_jobject(r0, rscratch1, rscratch2);
3324   __ leave();
3325   __ ret(lr);
3326 
3327   OopMap* map = new OopMap(framesize, 1); // rfp
3328   oop_maps->add_gc_map(the_pc - start, map);
3329 
3330   RuntimeStub* stub = // codeBlob framesize is in words (not VMRegImpl::slot_size)
3331     RuntimeStub::new_runtime_stub(name, &code, frame_complete,
3332                                   (framesize >> (LogBytesPerWord - LogBytesPerInt)),
3333                                   oop_maps, false);
3334   return stub;
3335 }
3336 
3337 // For c2: call to return a leased buffer.
3338 RuntimeStub* SharedRuntime::generate_jfr_return_lease() {
3339   enum layout {
3340     rbp_off,
3341     rbpH_off,
3342     return_off,
3343     return_off2,
3344     framesize // inclusive of return address
3345   };
3346 
3347   int insts_size = 1024;
3348   int locs_size = 64;
3349 
3350   const char* name = SharedRuntime::stub_name(StubId::shared_jfr_return_lease_id);
3351   CodeBuffer code(name, insts_size, locs_size);
3352   OopMapSet* oop_maps = new OopMapSet();
3353   MacroAssembler* masm = new MacroAssembler(&code);
3354 
3355   address start = __ pc();
3356   __ enter();
3357   int frame_complete = __ pc() - start;
3358   address the_pc = __ pc();
3359   jfr_prologue(the_pc, masm, rthread);
3360   __ call_VM_leaf(CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::return_lease), 1);
3361   jfr_epilogue(masm);
3362 
3363   __ leave();
3364   __ ret(lr);
3365 
3366   OopMap* map = new OopMap(framesize, 1); // rfp
3367   oop_maps->add_gc_map(the_pc - start, map);
3368 
3369   RuntimeStub* stub = // codeBlob framesize is in words (not VMRegImpl::slot_size)
3370     RuntimeStub::new_runtime_stub(name, &code, frame_complete,
3371                                   (framesize >> (LogBytesPerWord - LogBytesPerInt)),
3372                                   oop_maps, false);
3373   return stub;
3374 }
3375 
3376 #endif // INCLUDE_JFR
--- EOF ---