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