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