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