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