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