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