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