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