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