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