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