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