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