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