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