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