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