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