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