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