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