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