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