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