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