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