1 /*
2 * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "cds/aotCompressedPointers.hpp"
26 #include "cds/archiveBuilder.hpp"
27 #include "cds/archiveUtils.inline.hpp"
28 #include "classfile/classLoader.hpp"
29 #include "classfile/compactHashtable.hpp"
30 #include "classfile/javaClasses.inline.hpp"
31 #include "classfile/stringTable.hpp"
32 #include "classfile/vmClasses.hpp"
33 #include "classfile/vmSymbols.hpp"
34 #include "code/aotCodeCache.hpp"
35 #include "code/codeCache.hpp"
36 #include "code/compiledIC.hpp"
37 #include "code/nmethod.inline.hpp"
38 #include "code/scopeDesc.hpp"
39 #include "code/vtableStubs.hpp"
40 #include "compiler/abstractCompiler.hpp"
41 #include "compiler/compileBroker.hpp"
42 #include "compiler/disassembler.hpp"
43 #include "gc/shared/barrierSet.hpp"
44 #include "gc/shared/collectedHeap.hpp"
45 #include "interpreter/interpreter.hpp"
46 #include "interpreter/interpreterRuntime.hpp"
47 #include "jfr/jfrEvents.hpp"
48 #include "jvm.h"
49 #include "logging/log.hpp"
50 #include "memory/oopFactory.hpp"
51 #include "memory/resourceArea.hpp"
52 #include "memory/universe.hpp"
53 #include "metaprogramming/primitiveConversions.hpp"
54 #include "oops/access.hpp"
55 #include "oops/fieldStreams.inline.hpp"
56 #include "oops/inlineKlass.inline.hpp"
57 #include "oops/klass.hpp"
58 #include "oops/method.inline.hpp"
59 #include "oops/objArrayKlass.hpp"
60 #include "oops/objArrayOop.inline.hpp"
61 #include "oops/oop.inline.hpp"
62 #include "prims/forte.hpp"
63 #include "prims/jvmtiExport.hpp"
64 #include "prims/jvmtiThreadState.hpp"
65 #include "prims/methodHandles.hpp"
66 #include "prims/nativeLookup.hpp"
67 #include "runtime/arguments.hpp"
68 #include "runtime/atomicAccess.hpp"
69 #include "runtime/basicLock.inline.hpp"
70 #include "runtime/frame.inline.hpp"
71 #include "runtime/handles.inline.hpp"
72 #include "runtime/init.hpp"
73 #include "runtime/interfaceSupport.inline.hpp"
74 #include "runtime/java.hpp"
75 #include "runtime/javaCalls.hpp"
76 #include "runtime/jniHandles.inline.hpp"
77 #include "runtime/osThread.hpp"
78 #include "runtime/perfData.hpp"
79 #include "runtime/sharedRuntime.hpp"
80 #include "runtime/signature.hpp"
81 #include "runtime/stackWatermarkSet.hpp"
82 #include "runtime/stubRoutines.hpp"
83 #include "runtime/synchronizer.hpp"
84 #include "runtime/timerTrace.hpp"
85 #include "runtime/vframe.inline.hpp"
86 #include "runtime/vframeArray.hpp"
87 #include "runtime/vm_version.hpp"
88 #include "utilities/copy.hpp"
89 #include "utilities/dtrace.hpp"
90 #include "utilities/events.hpp"
91 #include "utilities/globalDefinitions.hpp"
92 #include "utilities/hashTable.hpp"
93 #include "utilities/macros.hpp"
94 #include "utilities/xmlstream.hpp"
95 #ifdef COMPILER1
96 #include "c1/c1_Runtime1.hpp"
97 #endif
98 #ifdef COMPILER2
99 #include "opto/runtime.hpp"
100 #endif
101 #if INCLUDE_JFR
102 #include "jfr/jfr.inline.hpp"
103 #endif
104
105 // Shared runtime stub routines reside in their own unique blob with a
106 // single entry point
107
108
109 #define SHARED_STUB_FIELD_DEFINE(name, type) \
110 type* SharedRuntime::BLOB_FIELD_NAME(name);
111 SHARED_STUBS_DO(SHARED_STUB_FIELD_DEFINE)
112 #undef SHARED_STUB_FIELD_DEFINE
113
114 nmethod* SharedRuntime::_cont_doYield_stub;
115
116 #if 0
117 // TODO tweak global stub name generation to match this
118 #define SHARED_STUB_NAME_DECLARE(name, type) "Shared Runtime " # name "_blob",
119 const char *SharedRuntime::_stub_names[] = {
120 SHARED_STUBS_DO(SHARED_STUB_NAME_DECLARE)
121 };
122 #endif
123
124 //----------------------------generate_stubs-----------------------------------
125 void SharedRuntime::generate_initial_stubs() {
126 // Build this early so it's available for the interpreter.
127 _throw_StackOverflowError_blob =
128 generate_throw_exception(StubId::shared_throw_StackOverflowError_id,
129 CAST_FROM_FN_PTR(address, SharedRuntime::throw_StackOverflowError));
130 }
131
132 void SharedRuntime::generate_stubs() {
133 _wrong_method_blob =
134 generate_resolve_blob(StubId::shared_wrong_method_id,
135 CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method));
136 _wrong_method_abstract_blob =
137 generate_resolve_blob(StubId::shared_wrong_method_abstract_id,
138 CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_abstract));
139 _ic_miss_blob =
140 generate_resolve_blob(StubId::shared_ic_miss_id,
141 CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_ic_miss));
142 _resolve_opt_virtual_call_blob =
143 generate_resolve_blob(StubId::shared_resolve_opt_virtual_call_id,
144 CAST_FROM_FN_PTR(address, SharedRuntime::resolve_opt_virtual_call_C));
145 _resolve_virtual_call_blob =
146 generate_resolve_blob(StubId::shared_resolve_virtual_call_id,
147 CAST_FROM_FN_PTR(address, SharedRuntime::resolve_virtual_call_C));
148 _resolve_static_call_blob =
149 generate_resolve_blob(StubId::shared_resolve_static_call_id,
150 CAST_FROM_FN_PTR(address, SharedRuntime::resolve_static_call_C));
151
152 _throw_delayed_StackOverflowError_blob =
153 generate_throw_exception(StubId::shared_throw_delayed_StackOverflowError_id,
154 CAST_FROM_FN_PTR(address, SharedRuntime::throw_delayed_StackOverflowError));
155
156 _throw_AbstractMethodError_blob =
157 generate_throw_exception(StubId::shared_throw_AbstractMethodError_id,
158 CAST_FROM_FN_PTR(address, SharedRuntime::throw_AbstractMethodError));
159
160 _throw_IncompatibleClassChangeError_blob =
161 generate_throw_exception(StubId::shared_throw_IncompatibleClassChangeError_id,
162 CAST_FROM_FN_PTR(address, SharedRuntime::throw_IncompatibleClassChangeError));
163
164 _throw_NullPointerException_at_call_blob =
165 generate_throw_exception(StubId::shared_throw_NullPointerException_at_call_id,
166 CAST_FROM_FN_PTR(address, SharedRuntime::throw_NullPointerException_at_call));
167
168 #if COMPILER2_OR_JVMCI
169 // Vectors are generated only by C2 and JVMCI.
170 bool support_wide = is_wide_vector(MaxVectorSize);
171 if (support_wide) {
172 _polling_page_vectors_safepoint_handler_blob =
173 generate_handler_blob(StubId::shared_polling_page_vectors_safepoint_handler_id,
174 CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception));
175 }
176 #endif // COMPILER2_OR_JVMCI
177 _polling_page_safepoint_handler_blob =
178 generate_handler_blob(StubId::shared_polling_page_safepoint_handler_id,
179 CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception));
180 _polling_page_return_handler_blob =
181 generate_handler_blob(StubId::shared_polling_page_return_handler_id,
182 CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception));
183
184 generate_deopt_blob();
185 }
186
187 void SharedRuntime::init_adapter_library() {
188 AdapterHandlerLibrary::initialize();
189 }
190
191 #if INCLUDE_JFR
192 //------------------------------generate jfr runtime stubs ------
193 void SharedRuntime::generate_jfr_stubs() {
194 ResourceMark rm;
195 const char* timer_msg = "SharedRuntime generate_jfr_stubs";
196 TraceTime timer(timer_msg, TRACETIME_LOG(Info, startuptime));
197
198 _jfr_write_checkpoint_blob = generate_jfr_write_checkpoint();
199 _jfr_return_lease_blob = generate_jfr_return_lease();
200 }
201
202 #endif // INCLUDE_JFR
203
204 #include <math.h>
205
206 // Implementation of SharedRuntime
207
208 #ifndef PRODUCT
209 // For statistics
210 uint SharedRuntime::_ic_miss_ctr = 0;
211 uint SharedRuntime::_wrong_method_ctr = 0;
212 uint SharedRuntime::_resolve_static_ctr = 0;
213 uint SharedRuntime::_resolve_virtual_ctr = 0;
214 uint SharedRuntime::_resolve_opt_virtual_ctr = 0;
215 uint SharedRuntime::_implicit_null_throws = 0;
216 uint SharedRuntime::_implicit_div0_throws = 0;
217
218 int64_t SharedRuntime::_nof_normal_calls = 0;
219 int64_t SharedRuntime::_nof_inlined_calls = 0;
220 int64_t SharedRuntime::_nof_megamorphic_calls = 0;
221 int64_t SharedRuntime::_nof_static_calls = 0;
222 int64_t SharedRuntime::_nof_inlined_static_calls = 0;
223 int64_t SharedRuntime::_nof_interface_calls = 0;
224 int64_t SharedRuntime::_nof_inlined_interface_calls = 0;
225
226 uint SharedRuntime::_new_instance_ctr=0;
227 uint SharedRuntime::_new_array_ctr=0;
228 uint SharedRuntime::_multi2_ctr=0;
229 uint SharedRuntime::_multi3_ctr=0;
230 uint SharedRuntime::_multi4_ctr=0;
231 uint SharedRuntime::_multi5_ctr=0;
232 uint SharedRuntime::_mon_enter_stub_ctr=0;
233 uint SharedRuntime::_mon_exit_stub_ctr=0;
234 uint SharedRuntime::_mon_enter_ctr=0;
235 uint SharedRuntime::_mon_exit_ctr=0;
236 uint SharedRuntime::_partial_subtype_ctr=0;
237 uint SharedRuntime::_jbyte_array_copy_ctr=0;
238 uint SharedRuntime::_jshort_array_copy_ctr=0;
239 uint SharedRuntime::_jint_array_copy_ctr=0;
240 uint SharedRuntime::_jlong_array_copy_ctr=0;
241 uint SharedRuntime::_oop_array_copy_ctr=0;
242 uint SharedRuntime::_checkcast_array_copy_ctr=0;
243 uint SharedRuntime::_unsafe_array_copy_ctr=0;
244 uint SharedRuntime::_generic_array_copy_ctr=0;
245 uint SharedRuntime::_slow_array_copy_ctr=0;
246 uint SharedRuntime::_find_handler_ctr=0;
247 uint SharedRuntime::_rethrow_ctr=0;
248 uint SharedRuntime::_unsafe_set_memory_ctr=0;
249
250 int SharedRuntime::_ICmiss_index = 0;
251 int SharedRuntime::_ICmiss_count[SharedRuntime::maxICmiss_count];
252 address SharedRuntime::_ICmiss_at[SharedRuntime::maxICmiss_count];
253
254
255 void SharedRuntime::trace_ic_miss(address at) {
256 for (int i = 0; i < _ICmiss_index; i++) {
257 if (_ICmiss_at[i] == at) {
258 _ICmiss_count[i]++;
259 return;
260 }
261 }
262 int index = _ICmiss_index++;
263 if (_ICmiss_index >= maxICmiss_count) _ICmiss_index = maxICmiss_count - 1;
264 _ICmiss_at[index] = at;
265 _ICmiss_count[index] = 1;
266 }
267
268 void SharedRuntime::print_ic_miss_histogram() {
269 if (ICMissHistogram) {
270 tty->print_cr("IC Miss Histogram:");
271 int tot_misses = 0;
272 for (int i = 0; i < _ICmiss_index; i++) {
273 tty->print_cr(" at: " INTPTR_FORMAT " nof: %d", p2i(_ICmiss_at[i]), _ICmiss_count[i]);
274 tot_misses += _ICmiss_count[i];
275 }
276 tty->print_cr("Total IC misses: %7d", tot_misses);
277 }
278 }
279
280 #ifdef COMPILER2
281 // Runtime methods for printf-style debug nodes (same printing format as fieldDescriptor::print_on_for)
282 void SharedRuntime::debug_print_value(jboolean x) {
283 tty->print_cr("boolean %d", x);
284 }
285
286 void SharedRuntime::debug_print_value(jbyte x) {
287 tty->print_cr("byte %d", x);
288 }
289
290 void SharedRuntime::debug_print_value(jshort x) {
291 tty->print_cr("short %d", x);
292 }
293
294 void SharedRuntime::debug_print_value(jchar x) {
295 tty->print_cr("char %c %d", isprint(x) ? x : ' ', x);
296 }
297
298 void SharedRuntime::debug_print_value(jint x) {
299 tty->print_cr("int %d", x);
300 }
301
302 void SharedRuntime::debug_print_value(jlong x) {
303 tty->print_cr("long " JLONG_FORMAT, x);
304 }
305
306 void SharedRuntime::debug_print_value(jfloat x) {
307 tty->print_cr("float %f", x);
308 }
309
310 void SharedRuntime::debug_print_value(jdouble x) {
311 tty->print_cr("double %lf", x);
312 }
313
314 void SharedRuntime::debug_print_value(oopDesc* x) {
315 x->print();
316 }
317 #endif // COMPILER2
318
319 #endif // PRODUCT
320
321
322 JRT_LEAF(jlong, SharedRuntime::lmul(jlong y, jlong x))
323 return x * y;
324 JRT_END
325
326
327 JRT_LEAF(jlong, SharedRuntime::ldiv(jlong y, jlong x))
328 if (x == min_jlong && y == CONST64(-1)) {
329 return x;
330 } else {
331 return x / y;
332 }
333 JRT_END
334
335
336 JRT_LEAF(jlong, SharedRuntime::lrem(jlong y, jlong x))
337 if (x == min_jlong && y == CONST64(-1)) {
338 return 0;
339 } else {
340 return x % y;
341 }
342 JRT_END
343
344
345 #ifdef _WIN64
346 const juint float_sign_mask = 0x7FFFFFFF;
347 const juint float_infinity = 0x7F800000;
348 const julong double_sign_mask = CONST64(0x7FFFFFFFFFFFFFFF);
349 const julong double_infinity = CONST64(0x7FF0000000000000);
350 #endif
351
352 #if !defined(X86)
353 JRT_LEAF(jfloat, SharedRuntime::frem(jfloat x, jfloat y))
354 #ifdef _WIN64
355 // 64-bit Windows on amd64 returns the wrong values for
356 // infinity operands.
357 juint xbits = PrimitiveConversions::cast<juint>(x);
358 juint ybits = PrimitiveConversions::cast<juint>(y);
359 // x Mod Infinity == x unless x is infinity
360 if (((xbits & float_sign_mask) != float_infinity) &&
361 ((ybits & float_sign_mask) == float_infinity) ) {
362 return x;
363 }
364 return ((jfloat)fmod_winx64((double)x, (double)y));
365 #else
366 return ((jfloat)fmod((double)x,(double)y));
367 #endif
368 JRT_END
369
370 JRT_LEAF(jdouble, SharedRuntime::drem(jdouble x, jdouble y))
371 #ifdef _WIN64
372 julong xbits = PrimitiveConversions::cast<julong>(x);
373 julong ybits = PrimitiveConversions::cast<julong>(y);
374 // x Mod Infinity == x unless x is infinity
375 if (((xbits & double_sign_mask) != double_infinity) &&
376 ((ybits & double_sign_mask) == double_infinity) ) {
377 return x;
378 }
379 return ((jdouble)fmod_winx64((double)x, (double)y));
380 #else
381 return ((jdouble)fmod((double)x,(double)y));
382 #endif
383 JRT_END
384 #endif // !X86
385
386 JRT_LEAF(jfloat, SharedRuntime::i2f(jint x))
387 return (jfloat)x;
388 JRT_END
389
390 #ifdef __SOFTFP__
391 JRT_LEAF(jfloat, SharedRuntime::fadd(jfloat x, jfloat y))
392 return x + y;
393 JRT_END
394
395 JRT_LEAF(jfloat, SharedRuntime::fsub(jfloat x, jfloat y))
396 return x - y;
397 JRT_END
398
399 JRT_LEAF(jfloat, SharedRuntime::fmul(jfloat x, jfloat y))
400 return x * y;
401 JRT_END
402
403 JRT_LEAF(jfloat, SharedRuntime::fdiv(jfloat x, jfloat y))
404 return x / y;
405 JRT_END
406
407 JRT_LEAF(jdouble, SharedRuntime::dadd(jdouble x, jdouble y))
408 return x + y;
409 JRT_END
410
411 JRT_LEAF(jdouble, SharedRuntime::dsub(jdouble x, jdouble y))
412 return x - y;
413 JRT_END
414
415 JRT_LEAF(jdouble, SharedRuntime::dmul(jdouble x, jdouble y))
416 return x * y;
417 JRT_END
418
419 JRT_LEAF(jdouble, SharedRuntime::ddiv(jdouble x, jdouble y))
420 return x / y;
421 JRT_END
422
423 JRT_LEAF(jdouble, SharedRuntime::i2d(jint x))
424 return (jdouble)x;
425 JRT_END
426
427 JRT_LEAF(jdouble, SharedRuntime::f2d(jfloat x))
428 return (jdouble)x;
429 JRT_END
430
431 JRT_LEAF(int, SharedRuntime::fcmpl(float x, float y))
432 return x>y ? 1 : (x==y ? 0 : -1); /* x<y or is_nan*/
433 JRT_END
434
435 JRT_LEAF(int, SharedRuntime::fcmpg(float x, float y))
436 return x<y ? -1 : (x==y ? 0 : 1); /* x>y or is_nan */
437 JRT_END
438
439 JRT_LEAF(int, SharedRuntime::dcmpl(double x, double y))
440 return x>y ? 1 : (x==y ? 0 : -1); /* x<y or is_nan */
441 JRT_END
442
443 JRT_LEAF(int, SharedRuntime::dcmpg(double x, double y))
444 return x<y ? -1 : (x==y ? 0 : 1); /* x>y or is_nan */
445 JRT_END
446
447 // Functions to return the opposite of the aeabi functions for nan.
448 JRT_LEAF(int, SharedRuntime::unordered_fcmplt(float x, float y))
449 return (x < y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
450 JRT_END
451
452 JRT_LEAF(int, SharedRuntime::unordered_dcmplt(double x, double y))
453 return (x < y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
454 JRT_END
455
456 JRT_LEAF(int, SharedRuntime::unordered_fcmple(float x, float y))
457 return (x <= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
458 JRT_END
459
460 JRT_LEAF(int, SharedRuntime::unordered_dcmple(double x, double y))
461 return (x <= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
462 JRT_END
463
464 JRT_LEAF(int, SharedRuntime::unordered_fcmpge(float x, float y))
465 return (x >= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
466 JRT_END
467
468 JRT_LEAF(int, SharedRuntime::unordered_dcmpge(double x, double y))
469 return (x >= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
470 JRT_END
471
472 JRT_LEAF(int, SharedRuntime::unordered_fcmpgt(float x, float y))
473 return (x > y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
474 JRT_END
475
476 JRT_LEAF(int, SharedRuntime::unordered_dcmpgt(double x, double y))
477 return (x > y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
478 JRT_END
479
480 // Intrinsics make gcc generate code for these.
481 float SharedRuntime::fneg(float f) {
482 return -f;
483 }
484
485 double SharedRuntime::dneg(double f) {
486 return -f;
487 }
488
489 #endif // __SOFTFP__
490
491 #if defined(__SOFTFP__) || defined(E500V2)
492 // Intrinsics make gcc generate code for these.
493 double SharedRuntime::dabs(double f) {
494 return (f <= (double)0.0) ? (double)0.0 - f : f;
495 }
496
497 #endif
498
499 #if defined(__SOFTFP__)
500 double SharedRuntime::dsqrt(double f) {
501 return sqrt(f);
502 }
503 #endif
504
505 JRT_LEAF(jint, SharedRuntime::f2i(jfloat x))
506 if (g_isnan(x))
507 return 0;
508 if (x >= (jfloat) max_jint)
509 return max_jint;
510 if (x <= (jfloat) min_jint)
511 return min_jint;
512 return (jint) x;
513 JRT_END
514
515
516 JRT_LEAF(jlong, SharedRuntime::f2l(jfloat x))
517 if (g_isnan(x))
518 return 0;
519 if (x >= (jfloat) max_jlong)
520 return max_jlong;
521 if (x <= (jfloat) min_jlong)
522 return min_jlong;
523 return (jlong) x;
524 JRT_END
525
526
527 JRT_LEAF(jint, SharedRuntime::d2i(jdouble x))
528 if (g_isnan(x))
529 return 0;
530 if (x >= (jdouble) max_jint)
531 return max_jint;
532 if (x <= (jdouble) min_jint)
533 return min_jint;
534 return (jint) x;
535 JRT_END
536
537
538 JRT_LEAF(jlong, SharedRuntime::d2l(jdouble x))
539 if (g_isnan(x))
540 return 0;
541 if (x >= (jdouble) max_jlong)
542 return max_jlong;
543 if (x <= (jdouble) min_jlong)
544 return min_jlong;
545 return (jlong) x;
546 JRT_END
547
548
549 JRT_LEAF(jfloat, SharedRuntime::d2f(jdouble x))
550 return (jfloat)x;
551 JRT_END
552
553
554 JRT_LEAF(jfloat, SharedRuntime::l2f(jlong x))
555 return (jfloat)x;
556 JRT_END
557
558
559 JRT_LEAF(jdouble, SharedRuntime::l2d(jlong x))
560 return (jdouble)x;
561 JRT_END
562
563
564 // Exception handling across interpreter/compiler boundaries
565 //
566 // exception_handler_for_return_address(...) returns the continuation address.
567 // The continuation address is the entry point of the exception handler of the
568 // previous frame depending on the return address.
569
570 address SharedRuntime::raw_exception_handler_for_return_address(JavaThread* current, address return_address) {
571 // Note: This is called when we have unwound the frame of the callee that did
572 // throw an exception. So far, no check has been performed by the StackWatermarkSet.
573 // Notably, the stack is not walkable at this point, and hence the check must
574 // be deferred until later. Specifically, any of the handlers returned here in
575 // this function, will get dispatched to, and call deferred checks to
576 // StackWatermarkSet::after_unwind at a point where the stack is walkable.
577 assert(frame::verify_return_pc(return_address), "must be a return address: " INTPTR_FORMAT, p2i(return_address));
578 assert(current->frames_to_pop_failed_realloc() == 0 || Interpreter::contains(return_address), "missed frames to pop?");
579
580 #if INCLUDE_JVMCI
581 // JVMCI's ExceptionHandlerStub expects the thread local exception PC to be clear
582 // and other exception handler continuations do not read it
583 current->set_exception_pc(nullptr);
584 #endif // INCLUDE_JVMCI
585
586 if (Continuation::is_return_barrier_entry(return_address)) {
587 return StubRoutines::cont_returnBarrierExc();
588 }
589
590 // The fastest case first
591 CodeBlob* blob = CodeCache::find_blob(return_address);
592 nmethod* nm = (blob != nullptr) ? blob->as_nmethod_or_null() : nullptr;
593 if (nm != nullptr) {
594 // native nmethods don't have exception handlers
595 assert(!nm->is_native_method() || nm->method()->is_continuation_enter_intrinsic(), "no exception handler");
596 assert(nm->header_begin() != nm->exception_begin(), "no exception handler");
597 if (nm->is_deopt_pc(return_address)) {
598 // If we come here because of a stack overflow, the stack may be
599 // unguarded. Reguard the stack otherwise if we return to the
600 // deopt blob and the stack bang causes a stack overflow we
601 // crash.
602 StackOverflow* overflow_state = current->stack_overflow_state();
603 bool guard_pages_enabled = overflow_state->reguard_stack_if_needed();
604 if (overflow_state->reserved_stack_activation() != current->stack_base()) {
605 overflow_state->set_reserved_stack_activation(current->stack_base());
606 }
607 assert(guard_pages_enabled, "stack banging in deopt blob may cause crash");
608 // The deferred StackWatermarkSet::after_unwind check will be performed in
609 // Deoptimization::fetch_unroll_info (with exec_mode == Unpack_exception)
610 return SharedRuntime::deopt_blob()->unpack_with_exception();
611 } else {
612 // The deferred StackWatermarkSet::after_unwind check will be performed in
613 // * OptoRuntime::handle_exception_C_helper for C2 code
614 // * exception_handler_for_pc_helper via Runtime1::handle_exception_from_callee_id for C1 code
615 #ifdef COMPILER2
616 if (nm->compiler_type() == compiler_c2) {
617 return OptoRuntime::exception_blob()->entry_point();
618 }
619 #endif // COMPILER2
620 return nm->exception_begin();
621 }
622 }
623
624 // Entry code
625 if (StubRoutines::returns_to_call_stub(return_address)) {
626 // The deferred StackWatermarkSet::after_unwind check will be performed in
627 // JavaCallWrapper::~JavaCallWrapper
628 assert (StubRoutines::catch_exception_entry() != nullptr, "must be generated before");
629 return StubRoutines::catch_exception_entry();
630 }
631 if (blob != nullptr && blob->is_upcall_stub()) {
632 return StubRoutines::upcall_stub_exception_handler();
633 }
634 // Interpreted code
635 if (Interpreter::contains(return_address)) {
636 // The deferred StackWatermarkSet::after_unwind check will be performed in
637 // InterpreterRuntime::exception_handler_for_exception
638 return Interpreter::rethrow_exception_entry();
639 }
640
641 guarantee(blob == nullptr || !blob->is_runtime_stub(), "caller should have skipped stub");
642 guarantee(!VtableStubs::contains(return_address), "null exceptions in vtables should have been handled already!");
643
644 #ifndef PRODUCT
645 { ResourceMark rm;
646 tty->print_cr("No exception handler found for exception at " INTPTR_FORMAT " - potential problems:", p2i(return_address));
647 os::print_location(tty, (intptr_t)return_address);
648 tty->print_cr("a) exception happened in (new?) code stubs/buffers that is not handled here");
649 tty->print_cr("b) other problem");
650 }
651 #endif // PRODUCT
652 ShouldNotReachHere();
653 return nullptr;
654 }
655
656
657 JRT_LEAF(address, SharedRuntime::exception_handler_for_return_address(JavaThread* current, address return_address))
658 return raw_exception_handler_for_return_address(current, return_address);
659 JRT_END
660
661
662 address SharedRuntime::get_poll_stub(address pc) {
663 address stub;
664 // Look up the code blob
665 CodeBlob *cb = CodeCache::find_blob(pc);
666
667 // Should be an nmethod
668 guarantee(cb != nullptr && cb->is_nmethod(), "safepoint polling: pc must refer to an nmethod");
669
670 // Look up the relocation information
671 assert(cb->as_nmethod()->is_at_poll_or_poll_return(pc),
672 "safepoint polling: type must be poll at pc " INTPTR_FORMAT, p2i(pc));
673
674 #ifdef ASSERT
675 if (!((NativeInstruction*)pc)->is_safepoint_poll()) {
676 tty->print_cr("bad pc: " PTR_FORMAT, p2i(pc));
677 Disassembler::decode(cb);
678 fatal("Only polling locations are used for safepoint");
679 }
680 #endif
681
682 bool at_poll_return = cb->as_nmethod()->is_at_poll_return(pc);
683 bool has_wide_vectors = cb->as_nmethod()->has_wide_vectors();
684 if (at_poll_return) {
685 assert(SharedRuntime::polling_page_return_handler_blob() != nullptr,
686 "polling page return stub not created yet");
687 stub = SharedRuntime::polling_page_return_handler_blob()->entry_point();
688 } else if (has_wide_vectors) {
689 assert(SharedRuntime::polling_page_vectors_safepoint_handler_blob() != nullptr,
690 "polling page vectors safepoint stub not created yet");
691 stub = SharedRuntime::polling_page_vectors_safepoint_handler_blob()->entry_point();
692 } else {
693 assert(SharedRuntime::polling_page_safepoint_handler_blob() != nullptr,
694 "polling page safepoint stub not created yet");
695 stub = SharedRuntime::polling_page_safepoint_handler_blob()->entry_point();
696 }
697 log_trace(safepoint)("Polling page exception: thread = " INTPTR_FORMAT " [%d], pc = "
698 INTPTR_FORMAT " (%s), stub = " INTPTR_FORMAT,
699 p2i(Thread::current()),
700 Thread::current()->osthread()->thread_id(),
701 p2i(pc),
702 at_poll_return ? "return" : "loop",
703 p2i(stub));
704 return stub;
705 }
706
707 void SharedRuntime::throw_and_post_jvmti_exception(JavaThread* current, Handle h_exception) {
708 if (JvmtiExport::can_post_on_exceptions()) {
709 vframeStream vfst(current, true);
710 methodHandle method = methodHandle(current, vfst.method());
711 address bcp = method()->bcp_from(vfst.bci());
712 JvmtiExport::post_exception_throw(current, method(), bcp, h_exception());
713 }
714
715 #if INCLUDE_JVMCI
716 if (EnableJVMCI) {
717 vframeStream vfst(current, true);
718 methodHandle method = methodHandle(current, vfst.method());
719 int bci = vfst.bci();
720 MethodData* trap_mdo = method->method_data();
721 if (trap_mdo != nullptr) {
722 // Set exception_seen if the exceptional bytecode is an invoke
723 Bytecode_invoke call = Bytecode_invoke_check(method, bci);
724 if (call.is_valid()) {
725 ResourceMark rm(current);
726
727 // Lock to read ProfileData, and ensure lock is not broken by a safepoint
728 MutexLocker ml(trap_mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
729
730 ProfileData* pdata = trap_mdo->allocate_bci_to_data(bci, nullptr);
731 if (pdata != nullptr && pdata->is_BitData()) {
732 BitData* bit_data = (BitData*) pdata;
733 bit_data->set_exception_seen();
734 }
735 }
736 }
737 }
738 #endif
739
740 Exceptions::_throw(current, __FILE__, __LINE__, h_exception);
741 }
742
743 void SharedRuntime::throw_and_post_jvmti_exception(JavaThread* current, Symbol* name, const char *message) {
744 Handle h_exception = Exceptions::new_exception(current, name, message);
745 throw_and_post_jvmti_exception(current, h_exception);
746 }
747
748 // The interpreter code to call this tracing function is only
749 // called/generated when UL is on for redefine, class and has the right level
750 // and tags. Since obsolete methods are never compiled, we don't have
751 // to modify the compilers to generate calls to this function.
752 //
753 JRT_LEAF(int, SharedRuntime::rc_trace_method_entry(
754 JavaThread* thread, Method* method))
755 if (method->is_obsolete()) {
756 // We are calling an obsolete method, but this is not necessarily
757 // an error. Our method could have been redefined just after we
758 // fetched the Method* from the constant pool.
759 ResourceMark rm;
760 log_trace(redefine, class, obsolete)("calling obsolete method '%s'", method->name_and_sig_as_C_string());
761 }
762 return 0;
763 JRT_END
764
765 // ret_pc points into caller; we are returning caller's exception handler
766 // for given exception
767 // Note that the implementation of this method assumes it's only called when an exception has actually occured
768 address SharedRuntime::compute_compiled_exc_handler(nmethod* nm, address ret_pc, Handle& exception,
769 bool force_unwind, bool top_frame_only, bool& recursive_exception_occurred) {
770 assert(nm != nullptr, "must exist");
771 ResourceMark rm;
772
773 #if INCLUDE_JVMCI
774 if (nm->is_compiled_by_jvmci()) {
775 // lookup exception handler for this pc
776 int catch_pco = pointer_delta_as_int(ret_pc, nm->code_begin());
777 ExceptionHandlerTable table(nm);
778 HandlerTableEntry *t = table.entry_for(catch_pco, -1, 0);
779 if (t != nullptr) {
780 return nm->code_begin() + t->pco();
781 } else {
782 bool make_not_entrant = true;
783 return Deoptimization::deoptimize_for_missing_exception_handler(nm, make_not_entrant);
784 }
785 }
786 #endif // INCLUDE_JVMCI
787
788 ScopeDesc* sd = nm->scope_desc_at(ret_pc);
789 // determine handler bci, if any
790 EXCEPTION_MARK;
791
792 Handle orig_exception(THREAD, exception());
793
794 int handler_bci = -1;
795 int scope_depth = 0;
796 if (!force_unwind) {
797 int bci = sd->bci();
798 bool recursive_exception = false;
799 do {
800 bool skip_scope_increment = false;
801 // exception handler lookup
802 Klass* ek = exception->klass();
803 methodHandle mh(THREAD, sd->method());
804 handler_bci = Method::fast_exception_handler_bci_for(mh, ek, bci, THREAD);
805 if (HAS_PENDING_EXCEPTION) {
806 recursive_exception = true;
807 // We threw an exception while trying to find the exception handler.
808 // Transfer the new exception to the exception handle which will
809 // be set into thread local storage, and do another lookup for an
810 // exception handler for this exception, this time starting at the
811 // BCI of the exception handler which caused the exception to be
812 // thrown (bugs 4307310 and 4546590). Set "exception" reference
813 // argument to ensure that the correct exception is thrown (4870175).
814 recursive_exception_occurred = true;
815 exception.replace(PENDING_EXCEPTION);
816 CLEAR_PENDING_EXCEPTION;
817 if (handler_bci >= 0) {
818 bci = handler_bci;
819 handler_bci = -1;
820 skip_scope_increment = true;
821 }
822 }
823 else {
824 recursive_exception = false;
825 }
826 if (!top_frame_only && handler_bci < 0 && !skip_scope_increment) {
827 sd = sd->sender();
828 if (sd != nullptr) {
829 bci = sd->bci();
830 }
831 ++scope_depth;
832 }
833 } while (recursive_exception || (!top_frame_only && handler_bci < 0 && sd != nullptr));
834 }
835
836 // found handling method => lookup exception handler
837 int catch_pco = pointer_delta_as_int(ret_pc, nm->code_begin());
838
839 ExceptionHandlerTable table(nm);
840 HandlerTableEntry *t = table.entry_for(catch_pco, handler_bci, scope_depth);
841
842 // If the compiler did not anticipate a recursive exception, resulting in an exception
843 // thrown from the catch bci, then the compiled exception handler might be missing.
844 // This is rare. Just deoptimize and let the interpreter rethrow the original
845 // exception at the original bci.
846 if (t == nullptr && recursive_exception_occurred) {
847 exception.replace(orig_exception()); // restore original exception
848 bool make_not_entrant = false;
849 return Deoptimization::deoptimize_for_missing_exception_handler(nm, make_not_entrant);
850 }
851
852 if (t == nullptr && (nm->is_compiled_by_c1() || handler_bci != -1)) {
853 // Allow abbreviated catch tables. The idea is to allow a method
854 // to materialize its exceptions without committing to the exact
855 // routing of exceptions. In particular this is needed for adding
856 // a synthetic handler to unlock monitors when inlining
857 // synchronized methods since the unlock path isn't represented in
858 // the bytecodes.
859 t = table.entry_for(catch_pco, -1, 0);
860 }
861
862 #ifdef COMPILER1
863 if (t == nullptr && nm->is_compiled_by_c1()) {
864 assert(nm->unwind_handler_begin() != nullptr, "");
865 return nm->unwind_handler_begin();
866 }
867 #endif
868
869 if (t == nullptr) {
870 ttyLocker ttyl;
871 tty->print_cr("MISSING EXCEPTION HANDLER for pc " INTPTR_FORMAT " and handler bci %d, catch_pco: %d", p2i(ret_pc), handler_bci, catch_pco);
872 tty->print_cr(" Exception:");
873 exception->print();
874 tty->cr();
875 tty->print_cr(" Compiled exception table :");
876 table.print();
877 nm->print();
878 nm->print_code();
879 guarantee(false, "missing exception handler");
880 return nullptr;
881 }
882
883 if (handler_bci != -1) { // did we find a handler in this method?
884 sd->method()->set_exception_handler_entered(handler_bci); // profile
885 }
886 return nm->code_begin() + t->pco();
887 }
888
889 JRT_ENTRY(void, SharedRuntime::throw_AbstractMethodError(JavaThread* current))
890 // These errors occur only at call sites
891 throw_and_post_jvmti_exception(current, vmSymbols::java_lang_AbstractMethodError());
892 JRT_END
893
894 JRT_ENTRY(void, SharedRuntime::throw_IncompatibleClassChangeError(JavaThread* current))
895 // These errors occur only at call sites
896 throw_and_post_jvmti_exception(current, vmSymbols::java_lang_IncompatibleClassChangeError(), "vtable stub");
897 JRT_END
898
899 JRT_ENTRY(void, SharedRuntime::throw_ArithmeticException(JavaThread* current))
900 throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ArithmeticException(), "/ by zero");
901 JRT_END
902
903 JRT_ENTRY(void, SharedRuntime::throw_NullPointerException(JavaThread* current))
904 throw_and_post_jvmti_exception(current, vmSymbols::java_lang_NullPointerException(), nullptr);
905 JRT_END
906
907 JRT_ENTRY(void, SharedRuntime::throw_NullPointerException_at_call(JavaThread* current))
908 // This entry point is effectively only used for NullPointerExceptions which occur at inline
909 // cache sites (when the callee activation is not yet set up) so we are at a call site
910 throw_and_post_jvmti_exception(current, vmSymbols::java_lang_NullPointerException(), nullptr);
911 JRT_END
912
913 JRT_ENTRY(void, SharedRuntime::throw_StackOverflowError(JavaThread* current))
914 throw_StackOverflowError_common(current, false);
915 JRT_END
916
917 JRT_ENTRY(void, SharedRuntime::throw_delayed_StackOverflowError(JavaThread* current))
918 throw_StackOverflowError_common(current, true);
919 JRT_END
920
921 void SharedRuntime::throw_StackOverflowError_common(JavaThread* current, bool delayed) {
922 // We avoid using the normal exception construction in this case because
923 // it performs an upcall to Java, and we're already out of stack space.
924 JavaThread* THREAD = current; // For exception macros.
925 InstanceKlass* k = vmClasses::StackOverflowError_klass();
926 oop exception_oop = k->allocate_instance(CHECK);
927 if (delayed) {
928 java_lang_Throwable::set_message(exception_oop,
929 Universe::delayed_stack_overflow_error_message());
930 }
931 Handle exception (current, exception_oop);
932 if (StackTraceInThrowable) {
933 java_lang_Throwable::fill_in_stack_trace(exception);
934 }
935 // Remove the ScopedValue bindings in case we got a
936 // StackOverflowError while we were trying to remove ScopedValue
937 // bindings.
938 current->clear_scopedValueBindings();
939 // Increment counter for hs_err file reporting
940 AtomicAccess::inc(&Exceptions::_stack_overflow_errors);
941 throw_and_post_jvmti_exception(current, exception);
942 }
943
944 address SharedRuntime::continuation_for_implicit_exception(JavaThread* current,
945 address pc,
946 ImplicitExceptionKind exception_kind)
947 {
948 address target_pc = nullptr;
949
950 if (Interpreter::contains(pc)) {
951 switch (exception_kind) {
952 case IMPLICIT_NULL: return Interpreter::throw_NullPointerException_entry();
953 case IMPLICIT_DIVIDE_BY_ZERO: return Interpreter::throw_ArithmeticException_entry();
954 case STACK_OVERFLOW: return Interpreter::throw_StackOverflowError_entry();
955 default: ShouldNotReachHere();
956 }
957 } else {
958 switch (exception_kind) {
959 case STACK_OVERFLOW: {
960 // Stack overflow only occurs upon frame setup; the callee is
961 // going to be unwound. Dispatch to a shared runtime stub
962 // which will cause the StackOverflowError to be fabricated
963 // and processed.
964 // Stack overflow should never occur during deoptimization:
965 // the compiled method bangs the stack by as much as the
966 // interpreter would need in case of a deoptimization. The
967 // deoptimization blob and uncommon trap blob bang the stack
968 // in a debug VM to verify the correctness of the compiled
969 // method stack banging.
970 assert(current->deopt_mark() == nullptr, "no stack overflow from deopt blob/uncommon trap");
971 Events::log_exception(current, "StackOverflowError at " INTPTR_FORMAT, p2i(pc));
972 return SharedRuntime::throw_StackOverflowError_entry();
973 }
974
975 case IMPLICIT_NULL: {
976 if (VtableStubs::contains(pc)) {
977 // We haven't yet entered the callee frame. Fabricate an
978 // exception and begin dispatching it in the caller. Since
979 // the caller was at a call site, it's safe to destroy all
980 // caller-saved registers, as these entry points do.
981 VtableStub* vt_stub = VtableStubs::stub_containing(pc);
982
983 // If vt_stub is null, then return null to signal handler to report the SEGV error.
984 if (vt_stub == nullptr) return nullptr;
985
986 if (vt_stub->is_abstract_method_error(pc)) {
987 assert(!vt_stub->is_vtable_stub(), "should never see AbstractMethodErrors from vtable-type VtableStubs");
988 Events::log_exception(current, "AbstractMethodError at " INTPTR_FORMAT, p2i(pc));
989 // Instead of throwing the abstract method error here directly, we re-resolve
990 // and will throw the AbstractMethodError during resolve. As a result, we'll
991 // get a more detailed error message.
992 return SharedRuntime::get_handle_wrong_method_stub();
993 } else {
994 Events::log_exception(current, "NullPointerException at vtable entry " INTPTR_FORMAT, p2i(pc));
995 // Assert that the signal comes from the expected location in stub code.
996 assert(vt_stub->is_null_pointer_exception(pc),
997 "obtained signal from unexpected location in stub code");
998 return SharedRuntime::throw_NullPointerException_at_call_entry();
999 }
1000 } else {
1001 CodeBlob* cb = CodeCache::find_blob(pc);
1002
1003 // If code blob is null, then return null to signal handler to report the SEGV error.
1004 if (cb == nullptr) return nullptr;
1005
1006 // Exception happened in CodeCache. Must be either:
1007 // 1. Inline-cache check in C2I handler blob,
1008 // 2. Inline-cache check in nmethod, or
1009 // 3. Implicit null exception in nmethod
1010
1011 if (!cb->is_nmethod()) {
1012 bool is_in_blob = cb->is_adapter_blob() || cb->is_method_handles_adapter_blob();
1013 if (!is_in_blob) {
1014 // Allow normal crash reporting to handle this
1015 return nullptr;
1016 }
1017 Events::log_exception(current, "NullPointerException in code blob at " INTPTR_FORMAT, p2i(pc));
1018 // There is no handler here, so we will simply unwind.
1019 return SharedRuntime::throw_NullPointerException_at_call_entry();
1020 }
1021
1022 // Otherwise, it's a compiled method. Consult its exception handlers.
1023 nmethod* nm = cb->as_nmethod();
1024 if (nm->inlinecache_check_contains(pc)) {
1025 // exception happened inside inline-cache check code
1026 // => the nmethod is not yet active (i.e., the frame
1027 // is not set up yet) => use return address pushed by
1028 // caller => don't push another return address
1029 Events::log_exception(current, "NullPointerException in IC check " INTPTR_FORMAT, p2i(pc));
1030 return SharedRuntime::throw_NullPointerException_at_call_entry();
1031 }
1032
1033 if (nm->method()->is_method_handle_intrinsic()) {
1034 // exception happened inside MH dispatch code, similar to a vtable stub
1035 Events::log_exception(current, "NullPointerException in MH adapter " INTPTR_FORMAT, p2i(pc));
1036 return SharedRuntime::throw_NullPointerException_at_call_entry();
1037 }
1038
1039 #ifndef PRODUCT
1040 _implicit_null_throws++;
1041 #endif
1042 target_pc = nm->continuation_for_implicit_null_exception(pc);
1043 // If there's an unexpected fault, target_pc might be null,
1044 // in which case we want to fall through into the normal
1045 // error handling code.
1046 }
1047
1048 break; // fall through
1049 }
1050
1051
1052 case IMPLICIT_DIVIDE_BY_ZERO: {
1053 nmethod* nm = CodeCache::find_nmethod(pc);
1054 guarantee(nm != nullptr, "must have containing compiled method for implicit division-by-zero exceptions");
1055 #ifndef PRODUCT
1056 _implicit_div0_throws++;
1057 #endif
1058 target_pc = nm->continuation_for_implicit_div0_exception(pc);
1059 // If there's an unexpected fault, target_pc might be null,
1060 // in which case we want to fall through into the normal
1061 // error handling code.
1062 break; // fall through
1063 }
1064
1065 default: ShouldNotReachHere();
1066 }
1067
1068 assert(exception_kind == IMPLICIT_NULL || exception_kind == IMPLICIT_DIVIDE_BY_ZERO, "wrong implicit exception kind");
1069
1070 if (exception_kind == IMPLICIT_NULL) {
1071 #ifndef PRODUCT
1072 // for AbortVMOnException flag
1073 Exceptions::debug_check_abort("java.lang.NullPointerException");
1074 #endif //PRODUCT
1075 Events::log_exception(current, "Implicit null exception at " INTPTR_FORMAT " to " INTPTR_FORMAT, p2i(pc), p2i(target_pc));
1076 } else {
1077 #ifndef PRODUCT
1078 // for AbortVMOnException flag
1079 Exceptions::debug_check_abort("java.lang.ArithmeticException");
1080 #endif //PRODUCT
1081 Events::log_exception(current, "Implicit division by zero exception at " INTPTR_FORMAT " to " INTPTR_FORMAT, p2i(pc), p2i(target_pc));
1082 }
1083 return target_pc;
1084 }
1085
1086 ShouldNotReachHere();
1087 return nullptr;
1088 }
1089
1090
1091 /**
1092 * Throws an java/lang/UnsatisfiedLinkError. The address of this method is
1093 * installed in the native function entry of all native Java methods before
1094 * they get linked to their actual native methods.
1095 *
1096 * \note
1097 * This method actually never gets called! The reason is because
1098 * the interpreter's native entries call NativeLookup::lookup() which
1099 * throws the exception when the lookup fails. The exception is then
1100 * caught and forwarded on the return from NativeLookup::lookup() call
1101 * before the call to the native function. This might change in the future.
1102 */
1103 JNI_ENTRY(void*, throw_unsatisfied_link_error(JNIEnv* env, ...))
1104 {
1105 // We return a bad value here to make sure that the exception is
1106 // forwarded before we look at the return value.
1107 THROW_(vmSymbols::java_lang_UnsatisfiedLinkError(), (void*)badAddress);
1108 }
1109 JNI_END
1110
1111 address SharedRuntime::native_method_throw_unsatisfied_link_error_entry() {
1112 return CAST_FROM_FN_PTR(address, &throw_unsatisfied_link_error);
1113 }
1114
1115 JRT_ENTRY_NO_ASYNC(void, SharedRuntime::register_finalizer(JavaThread* current, oopDesc* obj))
1116 #if INCLUDE_JVMCI
1117 if (!obj->klass()->has_finalizer()) {
1118 return;
1119 }
1120 #endif // INCLUDE_JVMCI
1121 assert(oopDesc::is_oop(obj), "must be a valid oop");
1122 assert(obj->klass()->has_finalizer(), "shouldn't be here otherwise");
1123 InstanceKlass::register_finalizer(instanceOop(obj), CHECK);
1124 JRT_END
1125
1126 jlong SharedRuntime::get_java_tid(JavaThread* thread) {
1127 assert(thread != nullptr, "No thread");
1128 if (thread == nullptr) {
1129 return 0;
1130 }
1131 guarantee(Thread::current() != thread || thread->is_oop_safe(),
1132 "current cannot touch oops after its GC barrier is detached.");
1133 oop obj = thread->threadObj();
1134 return (obj == nullptr) ? 0 : java_lang_Thread::thread_id(obj);
1135 }
1136
1137 /**
1138 * This function ought to be a void function, but cannot be because
1139 * it gets turned into a tail-call on sparc, which runs into dtrace bug
1140 * 6254741. Once that is fixed we can remove the dummy return value.
1141 */
1142 int SharedRuntime::dtrace_object_alloc(oopDesc* o) {
1143 return dtrace_object_alloc(JavaThread::current(), o, o->size());
1144 }
1145
1146 int SharedRuntime::dtrace_object_alloc(JavaThread* thread, oopDesc* o) {
1147 return dtrace_object_alloc(thread, o, o->size());
1148 }
1149
1150 int SharedRuntime::dtrace_object_alloc(JavaThread* thread, oopDesc* o, size_t size) {
1151 assert(DTraceAllocProbes, "wrong call");
1152 Klass* klass = o->klass();
1153 Symbol* name = klass->name();
1154 HOTSPOT_OBJECT_ALLOC(
1155 get_java_tid(thread),
1156 (char *) name->bytes(), name->utf8_length(), size * HeapWordSize);
1157 return 0;
1158 }
1159
1160 JRT_LEAF(int, SharedRuntime::dtrace_method_entry(
1161 JavaThread* current, Method* method))
1162 assert(current == JavaThread::current(), "pre-condition");
1163
1164 assert(DTraceMethodProbes, "wrong call");
1165 Symbol* kname = method->klass_name();
1166 Symbol* name = method->name();
1167 Symbol* sig = method->signature();
1168 HOTSPOT_METHOD_ENTRY(
1169 get_java_tid(current),
1170 (char *) kname->bytes(), kname->utf8_length(),
1171 (char *) name->bytes(), name->utf8_length(),
1172 (char *) sig->bytes(), sig->utf8_length());
1173 return 0;
1174 JRT_END
1175
1176 JRT_LEAF(int, SharedRuntime::dtrace_method_exit(
1177 JavaThread* current, Method* method))
1178 assert(current == JavaThread::current(), "pre-condition");
1179 assert(DTraceMethodProbes, "wrong call");
1180 Symbol* kname = method->klass_name();
1181 Symbol* name = method->name();
1182 Symbol* sig = method->signature();
1183 HOTSPOT_METHOD_RETURN(
1184 get_java_tid(current),
1185 (char *) kname->bytes(), kname->utf8_length(),
1186 (char *) name->bytes(), name->utf8_length(),
1187 (char *) sig->bytes(), sig->utf8_length());
1188 return 0;
1189 JRT_END
1190
1191
1192 // Finds receiver, CallInfo (i.e. receiver method), and calling bytecode)
1193 // for a call current in progress, i.e., arguments has been pushed on stack
1194 // put callee has not been invoked yet. Used by: resolve virtual/static,
1195 // vtable updates, etc. Caller frame must be compiled.
1196 Handle SharedRuntime::find_callee_info(Bytecodes::Code& bc, CallInfo& callinfo, TRAPS) {
1197 JavaThread* current = THREAD;
1198 ResourceMark rm(current);
1199
1200 // last java frame on stack (which includes native call frames)
1201 vframeStream vfst(current, true); // Do not skip and javaCalls
1202
1203 return find_callee_info_helper(vfst, bc, callinfo, THREAD);
1204 }
1205
1206 Method* SharedRuntime::extract_attached_method(vframeStream& vfst) {
1207 nmethod* caller = vfst.nm();
1208
1209 address pc = vfst.frame_pc();
1210 { // Get call instruction under lock because another thread may be busy patching it.
1211 CompiledICLocker ic_locker(caller);
1212 return caller->attached_method_before_pc(pc);
1213 }
1214 return nullptr;
1215 }
1216
1217 // Finds receiver, CallInfo (i.e. receiver method), and calling bytecode
1218 // for a call current in progress, i.e., arguments has been pushed on stack
1219 // but callee has not been invoked yet. Caller frame must be compiled.
1220 Handle SharedRuntime::find_callee_info_helper(vframeStream& vfst, Bytecodes::Code& bc,
1221 CallInfo& callinfo, TRAPS) {
1222 Handle receiver;
1223 Handle nullHandle; // create a handy null handle for exception returns
1224 JavaThread* current = THREAD;
1225
1226 assert(!vfst.at_end(), "Java frame must exist");
1227
1228 // Find caller and bci from vframe
1229 methodHandle caller(current, vfst.method());
1230 int bci = vfst.bci();
1231
1232 if (caller->is_continuation_enter_intrinsic()) {
1233 bc = Bytecodes::_invokestatic;
1234 LinkResolver::resolve_continuation_enter(callinfo, CHECK_NH);
1235 return receiver;
1236 }
1237
1238 // Substitutability test implementation piggy backs on static call resolution
1239 Bytecodes::Code code = caller->java_code_at(bci);
1240 if (code == Bytecodes::_if_acmpeq || code == Bytecodes::_if_acmpne) {
1241 bc = Bytecodes::_invokestatic;
1242 methodHandle attached_method(THREAD, extract_attached_method(vfst));
1243 assert(attached_method.not_null(), "must have attached method");
1244 vmClasses::ValueObjectMethods_klass()->initialize(CHECK_NH);
1245 LinkResolver::resolve_invoke(callinfo, receiver, attached_method, bc, false, CHECK_NH);
1246 #ifdef ASSERT
1247 Symbol* subst_method_name = vmSymbols::isSubstitutable_name();
1248 Method* is_subst = vmClasses::ValueObjectMethods_klass()->find_method(subst_method_name, vmSymbols::object_object_boolean_signature());
1249 assert(callinfo.selected_method() == is_subst, "must be isSubstitutable method");
1250 #endif
1251 return receiver;
1252 }
1253
1254 Bytecode_invoke bytecode(caller, bci);
1255 int bytecode_index = bytecode.index();
1256 bc = bytecode.invoke_code();
1257
1258 methodHandle attached_method(current, extract_attached_method(vfst));
1259 if (attached_method.not_null()) {
1260 Method* callee = bytecode.static_target(CHECK_NH);
1261 vmIntrinsics::ID id = callee->intrinsic_id();
1262 // When VM replaces MH.invokeBasic/linkTo* call with a direct/virtual call,
1263 // it attaches statically resolved method to the call site.
1264 if (MethodHandles::is_signature_polymorphic(id) &&
1265 MethodHandles::is_signature_polymorphic_intrinsic(id)) {
1266 bc = MethodHandles::signature_polymorphic_intrinsic_bytecode(id);
1267
1268 // Adjust invocation mode according to the attached method.
1269 switch (bc) {
1270 case Bytecodes::_invokevirtual:
1271 if (attached_method->method_holder()->is_interface()) {
1272 bc = Bytecodes::_invokeinterface;
1273 }
1274 break;
1275 case Bytecodes::_invokeinterface:
1276 if (!attached_method->method_holder()->is_interface()) {
1277 bc = Bytecodes::_invokevirtual;
1278 }
1279 break;
1280 case Bytecodes::_invokehandle:
1281 if (!MethodHandles::is_signature_polymorphic_method(attached_method())) {
1282 bc = attached_method->is_static() ? Bytecodes::_invokestatic
1283 : Bytecodes::_invokevirtual;
1284 }
1285 break;
1286 default:
1287 break;
1288 }
1289 } else {
1290 assert(attached_method->has_scalarized_args(), "invalid use of attached method");
1291 if (!attached_method->method_holder()->is_inline_klass()) {
1292 // Ignore the attached method in this case to not confuse below code
1293 attached_method = methodHandle(current, nullptr);
1294 }
1295 }
1296 }
1297
1298 assert(bc != Bytecodes::_illegal, "not initialized");
1299
1300 bool has_receiver = bc != Bytecodes::_invokestatic &&
1301 bc != Bytecodes::_invokedynamic &&
1302 bc != Bytecodes::_invokehandle;
1303 bool check_null_and_abstract = true;
1304
1305 // Find receiver for non-static call
1306 if (has_receiver) {
1307 // This register map must be update since we need to find the receiver for
1308 // compiled frames. The receiver might be in a register.
1309 RegisterMap reg_map2(current,
1310 RegisterMap::UpdateMap::include,
1311 RegisterMap::ProcessFrames::include,
1312 RegisterMap::WalkContinuation::skip);
1313 frame stubFrame = current->last_frame();
1314 // Caller-frame is a compiled frame
1315 frame callerFrame = stubFrame.sender(®_map2);
1316
1317 Method* callee = attached_method();
1318 if (callee == nullptr) {
1319 callee = bytecode.static_target(CHECK_NH);
1320 if (callee == nullptr) {
1321 THROW_(vmSymbols::java_lang_NoSuchMethodException(), nullHandle);
1322 }
1323 }
1324 bool caller_is_c1 = callerFrame.is_compiled_frame() && callerFrame.cb()->as_nmethod()->is_compiled_by_c1();
1325 if (!caller_is_c1 && callee->is_scalarized_arg(0)) {
1326 // If the receiver is an inline type that is passed as fields, no oop is available
1327 // Resolve the call without receiver null checking.
1328 assert(!callee->mismatch(), "calls with inline type receivers should never mismatch");
1329 assert(attached_method.not_null() && !attached_method->is_abstract(), "must have non-abstract attached method");
1330 if (bc == Bytecodes::_invokeinterface) {
1331 bc = Bytecodes::_invokevirtual; // C2 optimistically replaces interface calls by virtual calls
1332 }
1333 check_null_and_abstract = false;
1334 } else {
1335 // Retrieve from a compiled argument list
1336 receiver = Handle(current, callerFrame.retrieve_receiver(®_map2));
1337 assert(oopDesc::is_oop_or_null(receiver()), "");
1338 if (receiver.is_null()) {
1339 THROW_(vmSymbols::java_lang_NullPointerException(), nullHandle);
1340 }
1341 }
1342 }
1343
1344 // Resolve method
1345 if (attached_method.not_null()) {
1346 // Parameterized by attached method.
1347 LinkResolver::resolve_invoke(callinfo, receiver, attached_method, bc, check_null_and_abstract, CHECK_NH);
1348 } else {
1349 // Parameterized by bytecode.
1350 constantPoolHandle constants(current, caller->constants());
1351 LinkResolver::resolve_invoke(callinfo, receiver, constants, bytecode_index, bc, CHECK_NH);
1352 }
1353
1354 #ifdef ASSERT
1355 // Check that the receiver klass is of the right subtype and that it is initialized for virtual calls
1356 if (has_receiver && check_null_and_abstract) {
1357 assert(receiver.not_null(), "should have thrown exception");
1358 Klass* receiver_klass = receiver->klass();
1359 Klass* rk = nullptr;
1360 if (attached_method.not_null()) {
1361 // In case there's resolved method attached, use its holder during the check.
1362 rk = attached_method->method_holder();
1363 } else {
1364 // Klass is already loaded.
1365 constantPoolHandle constants(current, caller->constants());
1366 rk = constants->klass_ref_at(bytecode_index, bc, CHECK_NH);
1367 }
1368 Klass* static_receiver_klass = rk;
1369 assert(receiver_klass->is_subtype_of(static_receiver_klass),
1370 "actual receiver must be subclass of static receiver klass");
1371 if (receiver_klass->is_instance_klass()) {
1372 if (InstanceKlass::cast(receiver_klass)->is_not_initialized()) {
1373 tty->print_cr("ERROR: Klass not yet initialized!!");
1374 receiver_klass->print();
1375 }
1376 assert(!InstanceKlass::cast(receiver_klass)->is_not_initialized(), "receiver_klass must be initialized");
1377 }
1378 }
1379 #endif
1380
1381 return receiver;
1382 }
1383
1384 methodHandle SharedRuntime::find_callee_method(bool& caller_does_not_scalarize, TRAPS) {
1385 JavaThread* current = THREAD;
1386 ResourceMark rm(current);
1387 // We need first to check if any Java activations (compiled, interpreted)
1388 // exist on the stack since last JavaCall. If not, we need
1389 // to get the target method from the JavaCall wrapper.
1390 vframeStream vfst(current, true); // Do not skip any javaCalls
1391 methodHandle callee_method;
1392 if (vfst.at_end()) {
1393 // No Java frames were found on stack since we did the JavaCall.
1394 // Hence the stack can only contain an entry_frame. We need to
1395 // find the target method from the stub frame.
1396 RegisterMap reg_map(current,
1397 RegisterMap::UpdateMap::skip,
1398 RegisterMap::ProcessFrames::include,
1399 RegisterMap::WalkContinuation::skip);
1400 frame fr = current->last_frame();
1401 assert(fr.is_runtime_frame(), "must be a runtimeStub");
1402 fr = fr.sender(®_map);
1403 assert(fr.is_entry_frame(), "must be");
1404 // fr is now pointing to the entry frame.
1405 callee_method = methodHandle(current, fr.entry_frame_call_wrapper()->callee_method());
1406 } else {
1407 Bytecodes::Code bc;
1408 CallInfo callinfo;
1409 find_callee_info_helper(vfst, bc, callinfo, CHECK_(methodHandle()));
1410 // Calls via mismatching methods are always non-scalarized
1411 if (callinfo.resolved_method()->mismatch()) {
1412 caller_does_not_scalarize = true;
1413 }
1414 callee_method = methodHandle(current, callinfo.selected_method());
1415 }
1416 assert(callee_method()->is_method(), "must be");
1417 return callee_method;
1418 }
1419
1420 // Resolves a call.
1421 methodHandle SharedRuntime::resolve_helper(bool is_virtual, bool is_optimized, bool& caller_does_not_scalarize, TRAPS) {
1422 JavaThread* current = THREAD;
1423 ResourceMark rm(current);
1424 RegisterMap cbl_map(current,
1425 RegisterMap::UpdateMap::skip,
1426 RegisterMap::ProcessFrames::include,
1427 RegisterMap::WalkContinuation::skip);
1428 frame caller_frame = current->last_frame().sender(&cbl_map);
1429
1430 CodeBlob* caller_cb = caller_frame.cb();
1431 guarantee(caller_cb != nullptr && caller_cb->is_nmethod(), "must be called from compiled method");
1432 nmethod* caller_nm = caller_cb->as_nmethod();
1433
1434 // determine call info & receiver
1435 // note: a) receiver is null for static calls
1436 // b) an exception is thrown if receiver is null for non-static calls
1437 CallInfo call_info;
1438 Bytecodes::Code invoke_code = Bytecodes::_illegal;
1439 Handle receiver = find_callee_info(invoke_code, call_info, CHECK_(methodHandle()));
1440
1441 NoSafepointVerifier nsv;
1442
1443 methodHandle callee_method(current, call_info.selected_method());
1444 // Calls via mismatching methods are always non-scalarized
1445 if (caller_nm->is_compiled_by_c1() || call_info.resolved_method()->mismatch()) {
1446 caller_does_not_scalarize = true;
1447 }
1448
1449 assert((!is_virtual && invoke_code == Bytecodes::_invokestatic ) ||
1450 (!is_virtual && invoke_code == Bytecodes::_invokespecial) ||
1451 (!is_virtual && invoke_code == Bytecodes::_invokehandle ) ||
1452 (!is_virtual && invoke_code == Bytecodes::_invokedynamic) ||
1453 ( is_virtual && invoke_code != Bytecodes::_invokestatic ), "inconsistent bytecode");
1454
1455 assert(!caller_nm->is_unloading(), "It should not be unloading");
1456
1457 #ifndef PRODUCT
1458 // tracing/debugging/statistics
1459 uint *addr = (is_optimized) ? (&_resolve_opt_virtual_ctr) :
1460 (is_virtual) ? (&_resolve_virtual_ctr) :
1461 (&_resolve_static_ctr);
1462 AtomicAccess::inc(addr);
1463
1464 if (TraceCallFixup) {
1465 ResourceMark rm(current);
1466 tty->print("resolving %s%s (%s) %s call to",
1467 (is_optimized) ? "optimized " : "", (is_virtual) ? "virtual" : "static",
1468 Bytecodes::name(invoke_code), (caller_does_not_scalarize) ? "non-scalar" : "");
1469 callee_method->print_short_name(tty);
1470 tty->print_cr(" at pc: " INTPTR_FORMAT " to code: " INTPTR_FORMAT,
1471 p2i(caller_frame.pc()), p2i(callee_method->code()));
1472 }
1473 #endif
1474
1475 if (invoke_code == Bytecodes::_invokestatic) {
1476 assert(callee_method->method_holder()->is_initialized() ||
1477 callee_method->method_holder()->is_reentrant_initialization(current),
1478 "invalid class initialization state for invoke_static");
1479 if (!VM_Version::supports_fast_class_init_checks() && callee_method->needs_clinit_barrier()) {
1480 // In order to keep class initialization check, do not patch call
1481 // site for static call when the class is not fully initialized.
1482 // Proper check is enforced by call site re-resolution on every invocation.
1483 //
1484 // When fast class initialization checks are supported (VM_Version::supports_fast_class_init_checks() == true),
1485 // explicit class initialization check is put in nmethod entry (VEP).
1486 assert(callee_method->method_holder()->is_linked(), "must be");
1487 return callee_method;
1488 }
1489 }
1490
1491
1492 // JSR 292 key invariant:
1493 // If the resolved method is a MethodHandle invoke target, the call
1494 // site must be a MethodHandle call site, because the lambda form might tail-call
1495 // leaving the stack in a state unknown to either caller or callee
1496
1497 // Compute entry points. The computation of the entry points is independent of
1498 // patching the call.
1499
1500 // Make sure the callee nmethod does not get deoptimized and removed before
1501 // we are done patching the code.
1502
1503
1504 CompiledICLocker ml(caller_nm);
1505 if (is_virtual && !is_optimized) {
1506 CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc());
1507 inline_cache->update(&call_info, receiver->klass(), caller_does_not_scalarize);
1508 } else {
1509 // Callsite is a direct call - set it to the destination method
1510 CompiledDirectCall* callsite = CompiledDirectCall::before(caller_frame.pc());
1511 callsite->set(callee_method, caller_does_not_scalarize);
1512 }
1513
1514 return callee_method;
1515 }
1516
1517 // Inline caches exist only in compiled code
1518 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_ic_miss(JavaThread* current))
1519 #ifdef ASSERT
1520 RegisterMap reg_map(current,
1521 RegisterMap::UpdateMap::skip,
1522 RegisterMap::ProcessFrames::include,
1523 RegisterMap::WalkContinuation::skip);
1524 frame stub_frame = current->last_frame();
1525 assert(stub_frame.is_runtime_frame(), "sanity check");
1526 frame caller_frame = stub_frame.sender(®_map);
1527 assert(!caller_frame.is_interpreted_frame() && !caller_frame.is_entry_frame() && !caller_frame.is_upcall_stub_frame(), "unexpected frame");
1528 #endif /* ASSERT */
1529
1530 methodHandle callee_method;
1531 bool caller_does_not_scalarize = false;
1532 JRT_BLOCK
1533 callee_method = SharedRuntime::handle_ic_miss_helper(caller_does_not_scalarize, CHECK_NULL);
1534 // Return Method* through TLS
1535 current->set_vm_result_metadata(callee_method());
1536 JRT_BLOCK_END
1537 // return compiled code entry point after potential safepoints
1538 return get_resolved_entry(current, callee_method, false, false, caller_does_not_scalarize);
1539 JRT_END
1540
1541
1542 // Handle call site that has been made non-entrant
1543 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method(JavaThread* current))
1544 // 6243940 We might end up in here if the callee is deoptimized
1545 // as we race to call it. We don't want to take a safepoint if
1546 // the caller was interpreted because the caller frame will look
1547 // interpreted to the stack walkers and arguments are now
1548 // "compiled" so it is much better to make this transition
1549 // invisible to the stack walking code. The i2c path will
1550 // place the callee method in the callee_target. It is stashed
1551 // there because if we try and find the callee by normal means a
1552 // safepoint is possible and have trouble gc'ing the compiled args.
1553 RegisterMap reg_map(current,
1554 RegisterMap::UpdateMap::skip,
1555 RegisterMap::ProcessFrames::include,
1556 RegisterMap::WalkContinuation::skip);
1557 frame stub_frame = current->last_frame();
1558 assert(stub_frame.is_runtime_frame(), "sanity check");
1559 frame caller_frame = stub_frame.sender(®_map);
1560
1561 if (caller_frame.is_interpreted_frame() ||
1562 caller_frame.is_entry_frame() ||
1563 caller_frame.is_upcall_stub_frame()) {
1564 Method* callee = current->callee_target();
1565 guarantee(callee != nullptr && callee->is_method(), "bad handshake");
1566 current->set_vm_result_metadata(callee);
1567 current->set_callee_target(nullptr);
1568 if (caller_frame.is_entry_frame() && VM_Version::supports_fast_class_init_checks()) {
1569 // Bypass class initialization checks in c2i when caller is in native.
1570 // JNI calls to static methods don't have class initialization checks.
1571 // Fast class initialization checks are present in c2i adapters and call into
1572 // SharedRuntime::handle_wrong_method() on the slow path.
1573 //
1574 // JVM upcalls may land here as well, but there's a proper check present in
1575 // LinkResolver::resolve_static_call (called from JavaCalls::call_static),
1576 // so bypassing it in c2i adapter is benign.
1577 return callee->get_c2i_no_clinit_check_entry();
1578 } else {
1579 if (caller_frame.is_interpreted_frame()) {
1580 return callee->get_c2i_inline_entry();
1581 } else {
1582 return callee->get_c2i_entry();
1583 }
1584 }
1585 }
1586
1587 // Must be compiled to compiled path which is safe to stackwalk
1588 methodHandle callee_method;
1589 bool is_static_call = false;
1590 bool is_optimized = false;
1591 bool caller_does_not_scalarize = false;
1592 JRT_BLOCK
1593 // Force resolving of caller (if we called from compiled frame)
1594 callee_method = SharedRuntime::reresolve_call_site(is_optimized, caller_does_not_scalarize, CHECK_NULL);
1595 current->set_vm_result_metadata(callee_method());
1596 JRT_BLOCK_END
1597 // return compiled code entry point after potential safepoints
1598 return get_resolved_entry(current, callee_method, callee_method->is_static(), is_optimized, caller_does_not_scalarize);
1599 JRT_END
1600
1601 // Handle abstract method call
1602 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_abstract(JavaThread* current))
1603 // Verbose error message for AbstractMethodError.
1604 // Get the called method from the invoke bytecode.
1605 vframeStream vfst(current, true);
1606 assert(!vfst.at_end(), "Java frame must exist");
1607 methodHandle caller(current, vfst.method());
1608 Bytecode_invoke invoke(caller, vfst.bci());
1609 DEBUG_ONLY( invoke.verify(); )
1610
1611 // Find the compiled caller frame.
1612 RegisterMap reg_map(current,
1613 RegisterMap::UpdateMap::include,
1614 RegisterMap::ProcessFrames::include,
1615 RegisterMap::WalkContinuation::skip);
1616 frame stubFrame = current->last_frame();
1617 assert(stubFrame.is_runtime_frame(), "must be");
1618 frame callerFrame = stubFrame.sender(®_map);
1619 assert(callerFrame.is_compiled_frame(), "must be");
1620
1621 // Install exception and return forward entry.
1622 address res = SharedRuntime::throw_AbstractMethodError_entry();
1623 JRT_BLOCK
1624 methodHandle callee(current, invoke.static_target(current));
1625 if (!callee.is_null()) {
1626 oop recv = callerFrame.retrieve_receiver(®_map);
1627 Klass *recv_klass = (recv != nullptr) ? recv->klass() : nullptr;
1628 res = StubRoutines::forward_exception_entry();
1629 LinkResolver::throw_abstract_method_error(callee, recv_klass, CHECK_(res));
1630 }
1631 JRT_BLOCK_END
1632 return res;
1633 JRT_END
1634
1635 // return verified_code_entry if interp_only_mode is not set for the current thread;
1636 // otherwise return c2i entry.
1637 address SharedRuntime::get_resolved_entry(JavaThread* current, methodHandle callee_method,
1638 bool is_static_call, bool is_optimized, bool caller_does_not_scalarize) {
1639 bool is_interp_only_mode = (StressCallingConvention && (os::random() % (1 << 10)) == 0) || current->is_interp_only_mode();
1640 // In interp_only_mode we need to go to the interpreted entry
1641 // The c2i won't patch in this mode -- see fixup_callers_callsite
1642 bool go_to_interpreter = is_interp_only_mode && !callee_method->is_special_native_intrinsic();
1643
1644 if (caller_does_not_scalarize) {
1645 if (go_to_interpreter) {
1646 return callee_method->get_c2i_inline_entry();
1647 }
1648 assert(callee_method->verified_inline_code_entry() != nullptr, "Jump to zero!");
1649 return callee_method->verified_inline_code_entry();
1650 } else if (is_static_call || is_optimized) {
1651 if (go_to_interpreter) {
1652 return callee_method->get_c2i_entry();
1653 }
1654 assert(callee_method->verified_code_entry() != nullptr, "Jump to zero!");
1655 return callee_method->verified_code_entry();
1656 } else {
1657 if (go_to_interpreter) {
1658 return callee_method->get_c2i_inline_ro_entry();
1659 }
1660 assert(callee_method->verified_inline_ro_code_entry() != nullptr, "Jump to zero!");
1661 return callee_method->verified_inline_ro_code_entry();
1662 }
1663 }
1664
1665 // resolve a static call and patch code
1666 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_static_call_C(JavaThread* current ))
1667 methodHandle callee_method;
1668 bool caller_does_not_scalarize = false;
1669 bool enter_special = false;
1670 JRT_BLOCK
1671 callee_method = SharedRuntime::resolve_helper(false, false, caller_does_not_scalarize, CHECK_NULL);
1672 current->set_vm_result_metadata(callee_method());
1673 JRT_BLOCK_END
1674 // return compiled code entry point after potential safepoints
1675 return get_resolved_entry(current, callee_method, true, false, caller_does_not_scalarize);
1676 JRT_END
1677
1678 // resolve virtual call and update inline cache to monomorphic
1679 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_virtual_call_C(JavaThread* current))
1680 methodHandle callee_method;
1681 bool caller_does_not_scalarize = false;
1682 JRT_BLOCK
1683 callee_method = SharedRuntime::resolve_helper(true, false, caller_does_not_scalarize, CHECK_NULL);
1684 current->set_vm_result_metadata(callee_method());
1685 JRT_BLOCK_END
1686 // return compiled code entry point after potential safepoints
1687 return get_resolved_entry(current, callee_method, false, false, caller_does_not_scalarize);
1688 JRT_END
1689
1690
1691 // Resolve a virtual call that can be statically bound (e.g., always
1692 // monomorphic, so it has no inline cache). Patch code to resolved target.
1693 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_opt_virtual_call_C(JavaThread* current))
1694 methodHandle callee_method;
1695 bool caller_does_not_scalarize = false;
1696 JRT_BLOCK
1697 callee_method = SharedRuntime::resolve_helper(true, true, caller_does_not_scalarize, CHECK_NULL);
1698 current->set_vm_result_metadata(callee_method());
1699 JRT_BLOCK_END
1700 // return compiled code entry point after potential safepoints
1701 return get_resolved_entry(current, callee_method, false, true, caller_does_not_scalarize);
1702 JRT_END
1703
1704
1705
1706 methodHandle SharedRuntime::handle_ic_miss_helper(bool& caller_does_not_scalarize, TRAPS) {
1707 JavaThread* current = THREAD;
1708 ResourceMark rm(current);
1709 CallInfo call_info;
1710 Bytecodes::Code bc;
1711
1712 // receiver is null for static calls. An exception is thrown for null
1713 // receivers for non-static calls
1714 Handle receiver = find_callee_info(bc, call_info, CHECK_(methodHandle()));
1715
1716 methodHandle callee_method(current, call_info.selected_method());
1717
1718 #ifndef PRODUCT
1719 AtomicAccess::inc(&_ic_miss_ctr);
1720
1721 // Statistics & Tracing
1722 if (TraceCallFixup) {
1723 ResourceMark rm(current);
1724 tty->print("IC miss (%s) %s call to", Bytecodes::name(bc), (caller_does_not_scalarize) ? "non-scalar" : "");
1725 callee_method->print_short_name(tty);
1726 tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1727 }
1728
1729 if (ICMissHistogram) {
1730 MutexLocker m(VMStatistic_lock);
1731 RegisterMap reg_map(current,
1732 RegisterMap::UpdateMap::skip,
1733 RegisterMap::ProcessFrames::include,
1734 RegisterMap::WalkContinuation::skip);
1735 frame f = current->last_frame().real_sender(®_map);// skip runtime stub
1736 // produce statistics under the lock
1737 trace_ic_miss(f.pc());
1738 }
1739 #endif
1740
1741 // install an event collector so that when a vtable stub is created the
1742 // profiler can be notified via a DYNAMIC_CODE_GENERATED event. The
1743 // event can't be posted when the stub is created as locks are held
1744 // - instead the event will be deferred until the event collector goes
1745 // out of scope.
1746 JvmtiDynamicCodeEventCollector event_collector;
1747
1748 // Update inline cache to megamorphic. Skip update if we are called from interpreted.
1749 RegisterMap reg_map(current,
1750 RegisterMap::UpdateMap::skip,
1751 RegisterMap::ProcessFrames::include,
1752 RegisterMap::WalkContinuation::skip);
1753 frame caller_frame = current->last_frame().sender(®_map);
1754 CodeBlob* cb = caller_frame.cb();
1755 nmethod* caller_nm = cb->as_nmethod();
1756 // Calls via mismatching methods are always non-scalarized
1757 if (caller_nm->is_compiled_by_c1() || call_info.resolved_method()->mismatch()) {
1758 caller_does_not_scalarize = true;
1759 }
1760
1761 CompiledICLocker ml(caller_nm);
1762 CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc());
1763 inline_cache->update(&call_info, receiver()->klass(), caller_does_not_scalarize);
1764
1765 return callee_method;
1766 }
1767
1768 //
1769 // Resets a call-site in compiled code so it will get resolved again.
1770 // This routines handles both virtual call sites, optimized virtual call
1771 // sites, and static call sites. Typically used to change a call sites
1772 // destination from compiled to interpreted.
1773 //
1774 methodHandle SharedRuntime::reresolve_call_site(bool& is_optimized, bool& caller_does_not_scalarize, TRAPS) {
1775 JavaThread* current = THREAD;
1776 ResourceMark rm(current);
1777 RegisterMap reg_map(current,
1778 RegisterMap::UpdateMap::skip,
1779 RegisterMap::ProcessFrames::include,
1780 RegisterMap::WalkContinuation::skip);
1781 frame stub_frame = current->last_frame();
1782 assert(stub_frame.is_runtime_frame(), "must be a runtimeStub");
1783 frame caller = stub_frame.sender(®_map);
1784 if (caller.is_compiled_frame()) {
1785 caller_does_not_scalarize = caller.cb()->as_nmethod()->is_compiled_by_c1();
1786 }
1787 assert(!caller.is_interpreted_frame(), "must be compiled");
1788
1789 // If the frame isn't a live compiled frame (i.e. deoptimized by the time we get here), no IC clearing must be done
1790 // for the caller. However, when the caller is C2 compiled and the callee a C1 or C2 compiled method, then we still
1791 // need to figure out whether it was an optimized virtual call with an inline type receiver. Otherwise, we end up
1792 // using the wrong method entry point and accidentally skip the buffering of the receiver.
1793 methodHandle callee_method = find_callee_method(caller_does_not_scalarize, CHECK_(methodHandle()));
1794 const bool caller_is_compiled_and_not_deoptimized = caller.is_compiled_frame() && !caller.is_deoptimized_frame();
1795 const bool caller_is_continuation_enter_intrinsic =
1796 caller.is_native_frame() && caller.cb()->as_nmethod()->method()->is_continuation_enter_intrinsic();
1797 const bool do_IC_clearing = caller_is_compiled_and_not_deoptimized || caller_is_continuation_enter_intrinsic;
1798
1799 const bool callee_compiled_with_scalarized_receiver = callee_method->has_compiled_code() &&
1800 !callee_method()->is_static() &&
1801 callee_method()->is_scalarized_arg(0);
1802 const bool compute_is_optimized = !caller_does_not_scalarize && callee_compiled_with_scalarized_receiver;
1803
1804 if (do_IC_clearing || compute_is_optimized) {
1805 address pc = caller.pc();
1806
1807 nmethod* caller_nm = CodeCache::find_nmethod(pc);
1808 assert(caller_nm != nullptr, "did not find caller nmethod");
1809
1810 // Default call_addr is the location of the "basic" call.
1811 // Determine the address of the call we a reresolving. With
1812 // Inline Caches we will always find a recognizable call.
1813 // With Inline Caches disabled we may or may not find a
1814 // recognizable call. We will always find a call for static
1815 // calls and for optimized virtual calls. For vanilla virtual
1816 // calls it depends on the state of the UseInlineCaches switch.
1817 //
1818 // With Inline Caches disabled we can get here for a virtual call
1819 // for two reasons:
1820 // 1 - calling an abstract method. The vtable for abstract methods
1821 // will run us thru handle_wrong_method and we will eventually
1822 // end up in the interpreter to throw the ame.
1823 // 2 - a racing deoptimization. We could be doing a vanilla vtable
1824 // call and between the time we fetch the entry address and
1825 // we jump to it the target gets deoptimized. Similar to 1
1826 // we will wind up in the interprter (thru a c2i with c2).
1827 //
1828 CompiledICLocker ml(caller_nm);
1829 address call_addr = caller_nm->call_instruction_address(pc);
1830
1831 if (call_addr != nullptr) {
1832 // On x86 the logic for finding a call instruction is blindly checking for a call opcode 5
1833 // bytes back in the instruction stream so we must also check for reloc info.
1834 RelocIterator iter(caller_nm, call_addr, call_addr+1);
1835 bool ret = iter.next(); // Get item
1836 if (ret) {
1837 is_optimized = false;
1838 switch (iter.type()) {
1839 case relocInfo::static_call_type:
1840 assert(callee_method->is_static(), "must be");
1841 case relocInfo::opt_virtual_call_type: {
1842 is_optimized = (iter.type() == relocInfo::opt_virtual_call_type);
1843 if (do_IC_clearing) {
1844 CompiledDirectCall* cdc = CompiledDirectCall::at(call_addr);
1845 cdc->set_to_clean();
1846 }
1847 break;
1848 }
1849 case relocInfo::virtual_call_type: {
1850 if (do_IC_clearing) {
1851 // compiled, dispatched call (which used to call an interpreted method)
1852 CompiledIC* inline_cache = CompiledIC_at(caller_nm, call_addr);
1853 inline_cache->set_to_clean();
1854 }
1855 break;
1856 }
1857 default:
1858 break;
1859 }
1860 }
1861 }
1862 }
1863
1864 #ifndef PRODUCT
1865 AtomicAccess::inc(&_wrong_method_ctr);
1866
1867 if (TraceCallFixup) {
1868 ResourceMark rm(current);
1869 tty->print("handle_wrong_method reresolving %s call to", (caller_does_not_scalarize) ? "non-scalar" : "");
1870 callee_method->print_short_name(tty);
1871 tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1872 }
1873 #endif
1874
1875 return callee_method;
1876 }
1877
1878 address SharedRuntime::handle_unsafe_access(JavaThread* thread, address next_pc) {
1879 // The faulting unsafe accesses should be changed to throw the error
1880 // synchronously instead. Meanwhile the faulting instruction will be
1881 // skipped over (effectively turning it into a no-op) and an
1882 // asynchronous exception will be raised which the thread will
1883 // handle at a later point. If the instruction is a load it will
1884 // return garbage.
1885
1886 // Request an async exception.
1887 thread->set_pending_unsafe_access_error();
1888
1889 // Return address of next instruction to execute.
1890 return next_pc;
1891 }
1892
1893 #ifdef ASSERT
1894 void SharedRuntime::check_member_name_argument_is_last_argument(const methodHandle& method,
1895 const BasicType* sig_bt,
1896 const VMRegPair* regs) {
1897 ResourceMark rm;
1898 const int total_args_passed = method->size_of_parameters();
1899 const VMRegPair* regs_with_member_name = regs;
1900 VMRegPair* regs_without_member_name = NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed - 1);
1901
1902 const int member_arg_pos = total_args_passed - 1;
1903 assert(member_arg_pos >= 0 && member_arg_pos < total_args_passed, "oob");
1904 assert(sig_bt[member_arg_pos] == T_OBJECT, "dispatch argument must be an object");
1905
1906 java_calling_convention(sig_bt, regs_without_member_name, total_args_passed - 1);
1907
1908 for (int i = 0; i < member_arg_pos; i++) {
1909 VMReg a = regs_with_member_name[i].first();
1910 VMReg b = regs_without_member_name[i].first();
1911 assert(a->value() == b->value(), "register allocation mismatch: a= %d, b= %d", a->value(), b->value());
1912 }
1913 assert(regs_with_member_name[member_arg_pos].first()->is_valid(), "bad member arg");
1914 }
1915 #endif
1916
1917 // ---------------------------------------------------------------------------
1918 // We are calling the interpreter via a c2i. Normally this would mean that
1919 // we were called by a compiled method. However we could have lost a race
1920 // where we went int -> i2c -> c2i and so the caller could in fact be
1921 // interpreted. If the caller is compiled we attempt to patch the caller
1922 // so he no longer calls into the interpreter.
1923 JRT_LEAF(void, SharedRuntime::fixup_callers_callsite(Method* method, address caller_pc))
1924 AARCH64_PORT_ONLY(assert(pauth_ptr_is_raw(caller_pc), "should be raw"));
1925
1926 // It's possible that deoptimization can occur at a call site which hasn't
1927 // been resolved yet, in which case this function will be called from
1928 // an nmethod that has been patched for deopt and we can ignore the
1929 // request for a fixup.
1930 // Also it is possible that we lost a race in that from_compiled_entry
1931 // is now back to the i2c in that case we don't need to patch and if
1932 // we did we'd leap into space because the callsite needs to use
1933 // "to interpreter" stub in order to load up the Method*. Don't
1934 // ask me how I know this...
1935
1936 // Result from nmethod::is_unloading is not stable across safepoints.
1937 NoSafepointVerifier nsv;
1938
1939 nmethod* callee = method->code();
1940 if (callee == nullptr) {
1941 return;
1942 }
1943
1944 // write lock needed because we might patch call site by set_to_clean()
1945 // and is_unloading() can modify nmethod's state
1946 MACOS_AARCH64_ONLY(ThreadWXEnable __wx(WXWrite, JavaThread::current()));
1947
1948 CodeBlob* cb = CodeCache::find_blob(caller_pc);
1949 if (cb == nullptr || !cb->is_nmethod() || !callee->is_in_use() || callee->is_unloading()) {
1950 return;
1951 }
1952
1953 // The check above makes sure this is an nmethod.
1954 nmethod* caller = cb->as_nmethod();
1955
1956 // Get the return PC for the passed caller PC.
1957 address return_pc = caller_pc + frame::pc_return_offset;
1958
1959 if (!caller->is_in_use() || !NativeCall::is_call_before(return_pc)) {
1960 return;
1961 }
1962
1963 // Expect to find a native call there (unless it was no-inline cache vtable dispatch)
1964 CompiledICLocker ic_locker(caller);
1965 ResourceMark rm;
1966
1967 // If we got here through a static call or opt_virtual call, then we know where the
1968 // call address would be; let's peek at it
1969 address callsite_addr = (address)nativeCall_before(return_pc);
1970 RelocIterator iter(caller, callsite_addr, callsite_addr + 1);
1971 if (!iter.next()) {
1972 // No reloc entry found; not a static or optimized virtual call
1973 return;
1974 }
1975
1976 relocInfo::relocType type = iter.reloc()->type();
1977 if (type != relocInfo::static_call_type &&
1978 type != relocInfo::opt_virtual_call_type) {
1979 return;
1980 }
1981
1982 CompiledDirectCall* callsite = CompiledDirectCall::before(return_pc);
1983 callsite->set_to_clean();
1984 JRT_END
1985
1986
1987 // same as JVM_Arraycopy, but called directly from compiled code
1988 JRT_ENTRY(void, SharedRuntime::slow_arraycopy_C(oopDesc* src, jint src_pos,
1989 oopDesc* dest, jint dest_pos,
1990 jint length,
1991 JavaThread* current)) {
1992 #ifndef PRODUCT
1993 _slow_array_copy_ctr++;
1994 #endif
1995 // Check if we have null pointers
1996 if (src == nullptr || dest == nullptr) {
1997 THROW(vmSymbols::java_lang_NullPointerException());
1998 }
1999 // Do the copy. The casts to arrayOop are necessary to the copy_array API,
2000 // even though the copy_array API also performs dynamic checks to ensure
2001 // that src and dest are truly arrays (and are conformable).
2002 // The copy_array mechanism is awkward and could be removed, but
2003 // the compilers don't call this function except as a last resort,
2004 // so it probably doesn't matter.
2005 src->klass()->copy_array((arrayOopDesc*)src, src_pos,
2006 (arrayOopDesc*)dest, dest_pos,
2007 length, current);
2008 }
2009 JRT_END
2010
2011 // The caller of generate_class_cast_message() (or one of its callers)
2012 // must use a ResourceMark in order to correctly free the result.
2013 char* SharedRuntime::generate_class_cast_message(
2014 JavaThread* thread, Klass* caster_klass) {
2015
2016 // Get target class name from the checkcast instruction
2017 vframeStream vfst(thread, true);
2018 assert(!vfst.at_end(), "Java frame must exist");
2019 Bytecode_checkcast cc(vfst.method(), vfst.method()->bcp_from(vfst.bci()));
2020 constantPoolHandle cpool(thread, vfst.method()->constants());
2021 Klass* target_klass = ConstantPool::klass_at_if_loaded(cpool, cc.index());
2022 Symbol* target_klass_name = nullptr;
2023 if (target_klass == nullptr) {
2024 // This klass should be resolved, but just in case, get the name in the klass slot.
2025 target_klass_name = cpool->klass_name_at(cc.index());
2026 }
2027 return generate_class_cast_message(caster_klass, target_klass, target_klass_name);
2028 }
2029
2030
2031 // The caller of generate_class_cast_message() (or one of its callers)
2032 // must use a ResourceMark in order to correctly free the result.
2033 char* SharedRuntime::generate_class_cast_message(
2034 Klass* caster_klass, Klass* target_klass, Symbol* target_klass_name) {
2035 const char* caster_name = caster_klass->external_name();
2036
2037 assert(target_klass != nullptr || target_klass_name != nullptr, "one must be provided");
2038 const char* target_name = target_klass == nullptr ? target_klass_name->as_klass_external_name() :
2039 target_klass->external_name();
2040
2041 size_t msglen = strlen(caster_name) + strlen("class ") + strlen(" cannot be cast to class ") + strlen(target_name) + 1;
2042
2043 const char* caster_klass_description = "";
2044 const char* target_klass_description = "";
2045 const char* klass_separator = "";
2046 if (target_klass != nullptr && caster_klass->module() == target_klass->module()) {
2047 caster_klass_description = caster_klass->joint_in_module_of_loader(target_klass);
2048 } else {
2049 caster_klass_description = caster_klass->class_in_module_of_loader();
2050 target_klass_description = (target_klass != nullptr) ? target_klass->class_in_module_of_loader() : "";
2051 klass_separator = (target_klass != nullptr) ? "; " : "";
2052 }
2053
2054 // add 3 for parenthesis and preceding space
2055 msglen += strlen(caster_klass_description) + strlen(target_klass_description) + strlen(klass_separator) + 3;
2056
2057 char* message = NEW_RESOURCE_ARRAY_RETURN_NULL(char, msglen);
2058 if (message == nullptr) {
2059 // Shouldn't happen, but don't cause even more problems if it does
2060 message = const_cast<char*>(caster_klass->external_name());
2061 } else {
2062 jio_snprintf(message,
2063 msglen,
2064 "class %s cannot be cast to class %s (%s%s%s)",
2065 caster_name,
2066 target_name,
2067 caster_klass_description,
2068 klass_separator,
2069 target_klass_description
2070 );
2071 }
2072 return message;
2073 }
2074
2075 char* SharedRuntime::generate_identity_exception_message(JavaThread* current, Klass* klass) {
2076 assert(klass->is_inline_klass(), "Must be a concrete value class");
2077 const char* desc = "Cannot synchronize on an instance of value class ";
2078 const char* className = klass->external_name();
2079 size_t msglen = strlen(desc) + strlen(className) + 1;
2080 char* message = NEW_RESOURCE_ARRAY(char, msglen);
2081 if (nullptr == message) {
2082 // Out of memory: can't create detailed error message
2083 message = const_cast<char*>(klass->external_name());
2084 } else {
2085 jio_snprintf(message, msglen, "%s%s", desc, className);
2086 }
2087 return message;
2088 }
2089
2090 JRT_LEAF(void, SharedRuntime::reguard_yellow_pages())
2091 (void) JavaThread::current()->stack_overflow_state()->reguard_stack();
2092 JRT_END
2093
2094 void SharedRuntime::monitor_enter_helper(oopDesc* obj, BasicLock* lock, JavaThread* current) {
2095 if (!SafepointSynchronize::is_synchronizing()) {
2096 // Only try quick_enter() if we're not trying to reach a safepoint
2097 // so that the calling thread reaches the safepoint more quickly.
2098 if (ObjectSynchronizer::quick_enter(obj, lock, current)) {
2099 return;
2100 }
2101 }
2102 // NO_ASYNC required because an async exception on the state transition destructor
2103 // would leave you with the lock held and it would never be released.
2104 // The normal monitorenter NullPointerException is thrown without acquiring a lock
2105 // and the model is that an exception implies the method failed.
2106 JRT_BLOCK_NO_ASYNC
2107 Handle h_obj(THREAD, obj);
2108 ObjectSynchronizer::enter(h_obj, lock, current);
2109 assert(!HAS_PENDING_EXCEPTION, "Should have no exception here");
2110 JRT_BLOCK_END
2111 }
2112
2113 // Handles the uncommon case in locking, i.e., contention or an inflated lock.
2114 JRT_BLOCK_ENTRY(void, SharedRuntime::complete_monitor_locking_C(oopDesc* obj, BasicLock* lock, JavaThread* current))
2115 SharedRuntime::monitor_enter_helper(obj, lock, current);
2116 JRT_END
2117
2118 void SharedRuntime::monitor_exit_helper(oopDesc* obj, BasicLock* lock, JavaThread* current) {
2119 assert(JavaThread::current() == current, "invariant");
2120 // Exit must be non-blocking, and therefore no exceptions can be thrown.
2121 ExceptionMark em(current);
2122
2123 // Check if C2_MacroAssembler::fast_unlock() or
2124 // C2_MacroAssembler::fast_unlock() unlocked an inflated
2125 // monitor before going slow path. Since there is no safepoint
2126 // polling when calling into the VM, we can be sure that the monitor
2127 // hasn't been deallocated.
2128 ObjectMonitor* m = current->unlocked_inflated_monitor();
2129 if (m != nullptr) {
2130 assert(!m->has_owner(current), "must be");
2131 current->clear_unlocked_inflated_monitor();
2132
2133 // We need to reacquire the lock before we can call ObjectSynchronizer::exit().
2134 if (!m->try_enter(current, /*check_for_recursion*/ false)) {
2135 // Some other thread acquired the lock (or the monitor was
2136 // deflated). Either way we are done.
2137 return;
2138 }
2139 }
2140
2141 // The object could become unlocked through a JNI call, which we have no other checks for.
2142 // Give a fatal message if CheckJNICalls. Otherwise we ignore it.
2143 if (obj->is_unlocked()) {
2144 if (CheckJNICalls) {
2145 fatal("Object has been unlocked by JNI");
2146 }
2147 return;
2148 }
2149 ObjectSynchronizer::exit(obj, lock, current);
2150 }
2151
2152 // Handles the uncommon cases of monitor unlocking in compiled code
2153 JRT_LEAF(void, SharedRuntime::complete_monitor_unlocking_C(oopDesc* obj, BasicLock* lock, JavaThread* current))
2154 assert(current == JavaThread::current(), "pre-condition");
2155 SharedRuntime::monitor_exit_helper(obj, lock, current);
2156 JRT_END
2157
2158 #ifndef PRODUCT
2159
2160 void SharedRuntime::print_statistics() {
2161 ttyLocker ttyl;
2162 if (xtty != nullptr) xtty->head("statistics type='SharedRuntime'");
2163
2164 SharedRuntime::print_ic_miss_histogram();
2165
2166 // Dump the JRT_ENTRY counters
2167 if (_new_instance_ctr) tty->print_cr("%5u new instance requires GC", _new_instance_ctr);
2168 if (_new_array_ctr) tty->print_cr("%5u new array requires GC", _new_array_ctr);
2169 if (_multi2_ctr) tty->print_cr("%5u multianewarray 2 dim", _multi2_ctr);
2170 if (_multi3_ctr) tty->print_cr("%5u multianewarray 3 dim", _multi3_ctr);
2171 if (_multi4_ctr) tty->print_cr("%5u multianewarray 4 dim", _multi4_ctr);
2172 if (_multi5_ctr) tty->print_cr("%5u multianewarray 5 dim", _multi5_ctr);
2173
2174 tty->print_cr("%5u inline cache miss in compiled", _ic_miss_ctr);
2175 tty->print_cr("%5u wrong method", _wrong_method_ctr);
2176 tty->print_cr("%5u unresolved static call site", _resolve_static_ctr);
2177 tty->print_cr("%5u unresolved virtual call site", _resolve_virtual_ctr);
2178 tty->print_cr("%5u unresolved opt virtual call site", _resolve_opt_virtual_ctr);
2179
2180 if (_mon_enter_stub_ctr) tty->print_cr("%5u monitor enter stub", _mon_enter_stub_ctr);
2181 if (_mon_exit_stub_ctr) tty->print_cr("%5u monitor exit stub", _mon_exit_stub_ctr);
2182 if (_mon_enter_ctr) tty->print_cr("%5u monitor enter slow", _mon_enter_ctr);
2183 if (_mon_exit_ctr) tty->print_cr("%5u monitor exit slow", _mon_exit_ctr);
2184 if (_partial_subtype_ctr) tty->print_cr("%5u slow partial subtype", _partial_subtype_ctr);
2185 if (_jbyte_array_copy_ctr) tty->print_cr("%5u byte array copies", _jbyte_array_copy_ctr);
2186 if (_jshort_array_copy_ctr) tty->print_cr("%5u short array copies", _jshort_array_copy_ctr);
2187 if (_jint_array_copy_ctr) tty->print_cr("%5u int array copies", _jint_array_copy_ctr);
2188 if (_jlong_array_copy_ctr) tty->print_cr("%5u long array copies", _jlong_array_copy_ctr);
2189 if (_oop_array_copy_ctr) tty->print_cr("%5u oop array copies", _oop_array_copy_ctr);
2190 if (_checkcast_array_copy_ctr) tty->print_cr("%5u checkcast array copies", _checkcast_array_copy_ctr);
2191 if (_unsafe_array_copy_ctr) tty->print_cr("%5u unsafe array copies", _unsafe_array_copy_ctr);
2192 if (_generic_array_copy_ctr) tty->print_cr("%5u generic array copies", _generic_array_copy_ctr);
2193 if (_slow_array_copy_ctr) tty->print_cr("%5u slow array copies", _slow_array_copy_ctr);
2194 if (_find_handler_ctr) tty->print_cr("%5u find exception handler", _find_handler_ctr);
2195 if (_rethrow_ctr) tty->print_cr("%5u rethrow handler", _rethrow_ctr);
2196 if (_unsafe_set_memory_ctr) tty->print_cr("%5u unsafe set memorys", _unsafe_set_memory_ctr);
2197
2198 AdapterHandlerLibrary::print_statistics();
2199
2200 if (xtty != nullptr) xtty->tail("statistics");
2201 }
2202
2203 inline double percent(int64_t x, int64_t y) {
2204 return 100.0 * (double)x / (double)MAX2(y, (int64_t)1);
2205 }
2206
2207 class MethodArityHistogram {
2208 public:
2209 enum { MAX_ARITY = 256 };
2210 private:
2211 static uint64_t _arity_histogram[MAX_ARITY]; // histogram of #args
2212 static uint64_t _size_histogram[MAX_ARITY]; // histogram of arg size in words
2213 static uint64_t _total_compiled_calls;
2214 static uint64_t _max_compiled_calls_per_method;
2215 static int _max_arity; // max. arity seen
2216 static int _max_size; // max. arg size seen
2217
2218 static void add_method_to_histogram(nmethod* nm) {
2219 Method* method = (nm == nullptr) ? nullptr : nm->method();
2220 if (method != nullptr) {
2221 ArgumentCount args(method->signature());
2222 int arity = args.size() + (method->is_static() ? 0 : 1);
2223 int argsize = method->size_of_parameters();
2224 arity = MIN2(arity, MAX_ARITY-1);
2225 argsize = MIN2(argsize, MAX_ARITY-1);
2226 uint64_t count = (uint64_t)method->compiled_invocation_count();
2227 _max_compiled_calls_per_method = count > _max_compiled_calls_per_method ? count : _max_compiled_calls_per_method;
2228 _total_compiled_calls += count;
2229 _arity_histogram[arity] += count;
2230 _size_histogram[argsize] += count;
2231 _max_arity = MAX2(_max_arity, arity);
2232 _max_size = MAX2(_max_size, argsize);
2233 }
2234 }
2235
2236 void print_histogram_helper(int n, uint64_t* histo, const char* name) {
2237 const int N = MIN2(9, n);
2238 double sum = 0;
2239 double weighted_sum = 0;
2240 for (int i = 0; i <= n; i++) { sum += (double)histo[i]; weighted_sum += (double)(i*histo[i]); }
2241 if (sum >= 1) { // prevent divide by zero or divide overflow
2242 double rest = sum;
2243 double percent = sum / 100;
2244 for (int i = 0; i <= N; i++) {
2245 rest -= (double)histo[i];
2246 tty->print_cr("%4d: " UINT64_FORMAT_W(12) " (%5.1f%%)", i, histo[i], (double)histo[i] / percent);
2247 }
2248 tty->print_cr("rest: " INT64_FORMAT_W(12) " (%5.1f%%)", (int64_t)rest, rest / percent);
2249 tty->print_cr("(avg. %s = %3.1f, max = %d)", name, weighted_sum / sum, n);
2250 tty->print_cr("(total # of compiled calls = " INT64_FORMAT_W(14) ")", _total_compiled_calls);
2251 tty->print_cr("(max # of compiled calls = " INT64_FORMAT_W(14) ")", _max_compiled_calls_per_method);
2252 } else {
2253 tty->print_cr("Histogram generation failed for %s. n = %d, sum = %7.5f", name, n, sum);
2254 }
2255 }
2256
2257 void print_histogram() {
2258 tty->print_cr("\nHistogram of call arity (incl. rcvr, calls to compiled methods only):");
2259 print_histogram_helper(_max_arity, _arity_histogram, "arity");
2260 tty->print_cr("\nHistogram of parameter block size (in words, incl. rcvr):");
2261 print_histogram_helper(_max_size, _size_histogram, "size");
2262 tty->cr();
2263 }
2264
2265 public:
2266 MethodArityHistogram() {
2267 // Take the Compile_lock to protect against changes in the CodeBlob structures
2268 MutexLocker mu1(Compile_lock, Mutex::_safepoint_check_flag);
2269 // Take the CodeCache_lock to protect against changes in the CodeHeap structure
2270 MutexLocker mu2(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2271 _max_arity = _max_size = 0;
2272 _total_compiled_calls = 0;
2273 _max_compiled_calls_per_method = 0;
2274 for (int i = 0; i < MAX_ARITY; i++) _arity_histogram[i] = _size_histogram[i] = 0;
2275 CodeCache::nmethods_do(add_method_to_histogram);
2276 print_histogram();
2277 }
2278 };
2279
2280 uint64_t MethodArityHistogram::_arity_histogram[MethodArityHistogram::MAX_ARITY];
2281 uint64_t MethodArityHistogram::_size_histogram[MethodArityHistogram::MAX_ARITY];
2282 uint64_t MethodArityHistogram::_total_compiled_calls;
2283 uint64_t MethodArityHistogram::_max_compiled_calls_per_method;
2284 int MethodArityHistogram::_max_arity;
2285 int MethodArityHistogram::_max_size;
2286
2287 void SharedRuntime::print_call_statistics(uint64_t comp_total) {
2288 tty->print_cr("Calls from compiled code:");
2289 int64_t total = _nof_normal_calls + _nof_interface_calls + _nof_static_calls;
2290 int64_t mono_c = _nof_normal_calls - _nof_megamorphic_calls;
2291 int64_t mono_i = _nof_interface_calls;
2292 tty->print_cr("\t" INT64_FORMAT_W(12) " (100%%) total non-inlined ", total);
2293 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.1f%%) |- virtual calls ", _nof_normal_calls, percent(_nof_normal_calls, total));
2294 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- inlined ", _nof_inlined_calls, percent(_nof_inlined_calls, _nof_normal_calls));
2295 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- monomorphic ", mono_c, percent(mono_c, _nof_normal_calls));
2296 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- megamorphic ", _nof_megamorphic_calls, percent(_nof_megamorphic_calls, _nof_normal_calls));
2297 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.1f%%) |- interface calls ", _nof_interface_calls, percent(_nof_interface_calls, total));
2298 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- inlined ", _nof_inlined_interface_calls, percent(_nof_inlined_interface_calls, _nof_interface_calls));
2299 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- monomorphic ", mono_i, percent(mono_i, _nof_interface_calls));
2300 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.1f%%) |- static/special calls", _nof_static_calls, percent(_nof_static_calls, total));
2301 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- inlined ", _nof_inlined_static_calls, percent(_nof_inlined_static_calls, _nof_static_calls));
2302 tty->cr();
2303 tty->print_cr("Note 1: counter updates are not MT-safe.");
2304 tty->print_cr("Note 2: %% in major categories are relative to total non-inlined calls;");
2305 tty->print_cr(" %% in nested categories are relative to their category");
2306 tty->print_cr(" (and thus add up to more than 100%% with inlining)");
2307 tty->cr();
2308
2309 MethodArityHistogram h;
2310 }
2311 #endif
2312
2313 #ifndef PRODUCT
2314 static int _lookups; // number of calls to lookup
2315 static int _equals; // number of buckets checked with matching hash
2316 static int _archived_hits; // number of successful lookups in archived table
2317 static int _runtime_hits; // number of successful lookups in runtime table
2318 #endif
2319
2320 // A simple wrapper class around the calling convention information
2321 // that allows sharing of adapters for the same calling convention.
2322 class AdapterFingerPrint : public MetaspaceObj {
2323 public:
2324 class Element {
2325 private:
2326 // The highest byte is the type of the argument. The remaining bytes contain the offset of the
2327 // field if it is flattened in the calling convention, -1 otherwise.
2328 juint _payload;
2329
2330 static constexpr int offset_bit_width = 24;
2331 static constexpr juint offset_bit_mask = (1 << offset_bit_width) - 1;
2332 public:
2333 Element(BasicType bt, int offset) : _payload((static_cast<juint>(bt) << offset_bit_width) | (juint(offset) & offset_bit_mask)) {
2334 assert(offset >= -1 && offset < jint(offset_bit_mask), "invalid offset %d", offset);
2335 }
2336
2337 BasicType bt() const {
2338 return static_cast<BasicType>(_payload >> offset_bit_width);
2339 }
2340
2341 int offset() const {
2342 juint res = _payload & offset_bit_mask;
2343 return res == offset_bit_mask ? -1 : res;
2344 }
2345
2346 juint hash() const {
2347 return _payload;
2348 }
2349
2350 bool operator!=(const Element& other) const {
2351 return _payload != other._payload;
2352 }
2353 };
2354
2355 private:
2356 const bool _has_ro_adapter;
2357 const int _length;
2358
2359 static int data_offset() { return sizeof(AdapterFingerPrint); }
2360 Element* data_pointer() {
2361 return reinterpret_cast<Element*>(reinterpret_cast<address>(this) + data_offset());
2362 }
2363
2364 const Element& element_at(int index) {
2365 assert(index < length(), "index %d out of bounds for length %d", index, length());
2366 Element* data = data_pointer();
2367 return data[index];
2368 }
2369
2370 // Private construtor. Use allocate() to get an instance.
2371 AdapterFingerPrint(const GrowableArray<SigEntry>* sig, bool has_ro_adapter)
2372 : _has_ro_adapter(has_ro_adapter), _length(total_args_passed_in_sig(sig)) {
2373 Element* data = data_pointer();
2374 BasicType prev_bt = T_ILLEGAL;
2375 int vt_count = 0;
2376 for (int index = 0; index < _length; index++) {
2377 const SigEntry& sig_entry = sig->at(index);
2378 BasicType bt = sig_entry._bt;
2379 if (bt == T_METADATA) {
2380 // Found start of inline type in signature
2381 assert(InlineTypePassFieldsAsArgs, "unexpected start of inline type");
2382 vt_count++;
2383 } else if (bt == T_VOID && prev_bt != T_LONG && prev_bt != T_DOUBLE) {
2384 // Found end of inline type in signature
2385 assert(InlineTypePassFieldsAsArgs, "unexpected end of inline type");
2386 vt_count--;
2387 assert(vt_count >= 0, "invalid vt_count");
2388 } else if (vt_count == 0) {
2389 // Widen fields that are not part of a scalarized inline type argument
2390 assert(sig_entry._offset == -1, "invalid offset for argument that is not a flattened field %d", sig_entry._offset);
2391 bt = adapter_encoding(bt);
2392 }
2393
2394 ::new(&data[index]) Element(bt, sig_entry._offset);
2395 prev_bt = bt;
2396 }
2397 assert(vt_count == 0, "invalid vt_count");
2398 }
2399
2400 // Call deallocate instead
2401 ~AdapterFingerPrint() {
2402 ShouldNotCallThis();
2403 }
2404
2405 static int total_args_passed_in_sig(const GrowableArray<SigEntry>* sig) {
2406 return (sig != nullptr) ? sig->length() : 0;
2407 }
2408
2409 static int compute_size_in_words(int len) {
2410 return (int)heap_word_size(sizeof(AdapterFingerPrint) + (len * sizeof(Element)));
2411 }
2412
2413 // Remap BasicTypes that are handled equivalently by the adapters.
2414 // These are correct for the current system but someday it might be
2415 // necessary to make this mapping platform dependent.
2416 static BasicType adapter_encoding(BasicType in) {
2417 switch (in) {
2418 case T_BOOLEAN:
2419 case T_BYTE:
2420 case T_SHORT:
2421 case T_CHAR:
2422 // They are all promoted to T_INT in the calling convention
2423 return T_INT;
2424
2425 case T_OBJECT:
2426 case T_ARRAY:
2427 // In other words, we assume that any register good enough for
2428 // an int or long is good enough for a managed pointer.
2429 #ifdef _LP64
2430 return T_LONG;
2431 #else
2432 return T_INT;
2433 #endif
2434
2435 case T_INT:
2436 case T_LONG:
2437 case T_FLOAT:
2438 case T_DOUBLE:
2439 case T_VOID:
2440 return in;
2441
2442 default:
2443 ShouldNotReachHere();
2444 return T_CONFLICT;
2445 }
2446 }
2447
2448 void* operator new(size_t size, size_t fp_size) throw() {
2449 assert(fp_size >= size, "sanity check");
2450 void* p = AllocateHeap(fp_size, mtCode);
2451 memset(p, 0, fp_size);
2452 return p;
2453 }
2454
2455 public:
2456 template<typename Function>
2457 void iterate_args(Function function) {
2458 for (int i = 0; i < length(); i++) {
2459 function(element_at(i));
2460 }
2461 }
2462
2463 static AdapterFingerPrint* allocate(const GrowableArray<SigEntry>* sig, bool has_ro_adapter = false) {
2464 int len = total_args_passed_in_sig(sig);
2465 int size_in_bytes = BytesPerWord * compute_size_in_words(len);
2466 AdapterFingerPrint* afp = new (size_in_bytes) AdapterFingerPrint(sig, has_ro_adapter);
2467 assert((afp->size() * BytesPerWord) == size_in_bytes, "should match");
2468 return afp;
2469 }
2470
2471 static void deallocate(AdapterFingerPrint* fp) {
2472 FreeHeap(fp);
2473 }
2474
2475 bool has_ro_adapter() const {
2476 return _has_ro_adapter;
2477 }
2478
2479 int length() const {
2480 return _length;
2481 }
2482
2483 unsigned int compute_hash() {
2484 int hash = 0;
2485 for (int i = 0; i < length(); i++) {
2486 const Element& v = element_at(i);
2487 //Add arithmetic operation to the hash, like +3 to improve hashing
2488 hash = ((hash << 8) ^ v.hash() ^ (hash >> 5)) + 3;
2489 }
2490 return (unsigned int)hash;
2491 }
2492
2493 const char* as_string() {
2494 stringStream st;
2495 st.print("{");
2496 if (_has_ro_adapter) {
2497 st.print("has_ro_adapter");
2498 } else {
2499 st.print("no_ro_adapter");
2500 }
2501 for (int i = 0; i < length(); i++) {
2502 st.print(", ");
2503 const Element& elem = element_at(i);
2504 st.print("{%s, %d}", type2name(elem.bt()), elem.offset());
2505 }
2506 st.print("}");
2507 return st.as_string();
2508 }
2509
2510 const char* as_basic_args_string() {
2511 stringStream st;
2512 bool long_prev = false;
2513 iterate_args([&] (const Element& arg) {
2514 if (long_prev) {
2515 long_prev = false;
2516 if (arg.bt() == T_VOID) {
2517 st.print("J");
2518 } else {
2519 st.print("L");
2520 }
2521 }
2522 if (arg.bt() == T_LONG) {
2523 long_prev = true;
2524 } else if (arg.bt() != T_VOID) {
2525 st.print("%c", type2char(arg.bt()));
2526 }
2527 });
2528 if (long_prev) {
2529 st.print("L");
2530 }
2531 return st.as_string();
2532 }
2533
2534 bool equals(AdapterFingerPrint* other) {
2535 if (other->_has_ro_adapter != _has_ro_adapter) {
2536 return false;
2537 } else if (other->_length != _length) {
2538 return false;
2539 } else {
2540 for (int i = 0; i < _length; i++) {
2541 if (element_at(i) != other->element_at(i)) {
2542 return false;
2543 }
2544 }
2545 }
2546 return true;
2547 }
2548
2549 // methods required by virtue of being a MetaspaceObj
2550 void metaspace_pointers_do(MetaspaceClosure* it) { return; /* nothing to do here */ }
2551 int size() const { return compute_size_in_words(_length); }
2552 MetaspaceObj::Type type() const { return AdapterFingerPrintType; }
2553
2554 static bool equals(AdapterFingerPrint* const& fp1, AdapterFingerPrint* const& fp2) {
2555 NOT_PRODUCT(_equals++);
2556 return fp1->equals(fp2);
2557 }
2558
2559 static unsigned int compute_hash(AdapterFingerPrint* const& fp) {
2560 return fp->compute_hash();
2561 }
2562 };
2563
2564 #if INCLUDE_CDS
2565 static inline bool adapter_fp_equals_compact_hashtable_entry(AdapterHandlerEntry* entry, AdapterFingerPrint* fp, int len_unused) {
2566 return AdapterFingerPrint::equals(entry->fingerprint(), fp);
2567 }
2568
2569 class ArchivedAdapterTable : public OffsetCompactHashtable<
2570 AdapterFingerPrint*,
2571 AdapterHandlerEntry*,
2572 adapter_fp_equals_compact_hashtable_entry> {};
2573 #endif // INCLUDE_CDS
2574
2575 // A hashtable mapping from AdapterFingerPrints to AdapterHandlerEntries
2576 using AdapterHandlerTable = HashTable<AdapterFingerPrint*, AdapterHandlerEntry*, 293,
2577 AnyObj::C_HEAP, mtCode,
2578 AdapterFingerPrint::compute_hash,
2579 AdapterFingerPrint::equals>;
2580 static AdapterHandlerTable* _adapter_handler_table;
2581 static GrowableArray<AdapterHandlerEntry*>* _adapter_handler_list = nullptr;
2582
2583 // Find a entry with the same fingerprint if it exists
2584 AdapterHandlerEntry* AdapterHandlerLibrary::lookup(const GrowableArray<SigEntry>* sig, bool has_ro_adapter) {
2585 NOT_PRODUCT(_lookups++);
2586 assert_lock_strong(AdapterHandlerLibrary_lock);
2587 AdapterFingerPrint* fp = AdapterFingerPrint::allocate(sig, has_ro_adapter);
2588 AdapterHandlerEntry* entry = nullptr;
2589 #if INCLUDE_CDS
2590 // if we are building the archive then the archived adapter table is
2591 // not valid and we need to use the ones added to the runtime table
2592 if (AOTCodeCache::is_using_adapter()) {
2593 // Search archived table first. It is read-only table so can be searched without lock
2594 entry = _aot_adapter_handler_table.lookup(fp, fp->compute_hash(), 0 /* unused */);
2595 #ifndef PRODUCT
2596 if (entry != nullptr) {
2597 _archived_hits++;
2598 }
2599 #endif
2600 }
2601 #endif // INCLUDE_CDS
2602 if (entry == nullptr) {
2603 assert_lock_strong(AdapterHandlerLibrary_lock);
2604 AdapterHandlerEntry** entry_p = _adapter_handler_table->get(fp);
2605 if (entry_p != nullptr) {
2606 entry = *entry_p;
2607 assert(entry->fingerprint()->equals(fp), "fingerprint mismatch key fp %s %s (hash=%d) != found fp %s %s (hash=%d)",
2608 entry->fingerprint()->as_basic_args_string(), entry->fingerprint()->as_string(), entry->fingerprint()->compute_hash(),
2609 fp->as_basic_args_string(), fp->as_string(), fp->compute_hash());
2610 #ifndef PRODUCT
2611 _runtime_hits++;
2612 #endif
2613 }
2614 }
2615 AdapterFingerPrint::deallocate(fp);
2616 return entry;
2617 }
2618
2619 #ifndef PRODUCT
2620 static void print_table_statistics() {
2621 auto size = [&] (AdapterFingerPrint* key, AdapterHandlerEntry* a) {
2622 return sizeof(*key) + sizeof(*a);
2623 };
2624 TableStatistics ts = _adapter_handler_table->statistics_calculate(size);
2625 ts.print(tty, "AdapterHandlerTable");
2626 tty->print_cr("AdapterHandlerTable (table_size=%d, entries=%d)",
2627 _adapter_handler_table->table_size(), _adapter_handler_table->number_of_entries());
2628 int total_hits = _archived_hits + _runtime_hits;
2629 tty->print_cr("AdapterHandlerTable: lookups %d equals %d hits %d (archived=%d+runtime=%d)",
2630 _lookups, _equals, total_hits, _archived_hits, _runtime_hits);
2631 }
2632 #endif
2633
2634 // ---------------------------------------------------------------------------
2635 // Implementation of AdapterHandlerLibrary
2636 AdapterHandlerEntry* AdapterHandlerLibrary::_no_arg_handler = nullptr;
2637 AdapterHandlerEntry* AdapterHandlerLibrary::_int_arg_handler = nullptr;
2638 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_arg_handler = nullptr;
2639 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_int_arg_handler = nullptr;
2640 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_obj_arg_handler = nullptr;
2641 #if INCLUDE_CDS
2642 ArchivedAdapterTable AdapterHandlerLibrary::_aot_adapter_handler_table;
2643 #endif // INCLUDE_CDS
2644 static const int AdapterHandlerLibrary_size = 48*K;
2645 BufferBlob* AdapterHandlerLibrary::_buffer = nullptr;
2646 volatile uint AdapterHandlerLibrary::_id_counter = 0;
2647
2648 BufferBlob* AdapterHandlerLibrary::buffer_blob() {
2649 assert(_buffer != nullptr, "should be initialized");
2650 return _buffer;
2651 }
2652
2653 static void post_adapter_creation(const AdapterHandlerEntry* entry) {
2654 if (Forte::is_enabled() || JvmtiExport::should_post_dynamic_code_generated()) {
2655 AdapterBlob* adapter_blob = entry->adapter_blob();
2656 char blob_id[256];
2657 jio_snprintf(blob_id,
2658 sizeof(blob_id),
2659 "%s(%s)",
2660 adapter_blob->name(),
2661 entry->fingerprint()->as_string());
2662 if (Forte::is_enabled()) {
2663 Forte::register_stub(blob_id, adapter_blob->content_begin(), adapter_blob->content_end());
2664 }
2665
2666 if (JvmtiExport::should_post_dynamic_code_generated()) {
2667 JvmtiExport::post_dynamic_code_generated(blob_id, adapter_blob->content_begin(), adapter_blob->content_end());
2668 }
2669 }
2670 }
2671
2672 void AdapterHandlerLibrary::initialize() {
2673 {
2674 ResourceMark rm;
2675 _adapter_handler_table = new (mtCode) AdapterHandlerTable();
2676 _buffer = BufferBlob::create("adapters", AdapterHandlerLibrary_size);
2677 }
2678
2679 #if INCLUDE_CDS
2680 // Link adapters in AOT Cache to their code in AOT Code Cache
2681 if (AOTCodeCache::is_using_adapter() && !_aot_adapter_handler_table.empty()) {
2682 link_aot_adapters();
2683 lookup_simple_adapters();
2684 return;
2685 }
2686 #endif // INCLUDE_CDS
2687
2688 ResourceMark rm;
2689 {
2690 MutexLocker mu(AdapterHandlerLibrary_lock);
2691
2692 CompiledEntrySignature no_args;
2693 no_args.compute_calling_conventions();
2694 _no_arg_handler = create_adapter(no_args, true);
2695
2696 CompiledEntrySignature obj_args;
2697 SigEntry::add_entry(obj_args.sig(), T_OBJECT);
2698 obj_args.compute_calling_conventions();
2699 _obj_arg_handler = create_adapter(obj_args, true);
2700
2701 CompiledEntrySignature int_args;
2702 SigEntry::add_entry(int_args.sig(), T_INT);
2703 int_args.compute_calling_conventions();
2704 _int_arg_handler = create_adapter(int_args, true);
2705
2706 CompiledEntrySignature obj_int_args;
2707 SigEntry::add_entry(obj_int_args.sig(), T_OBJECT);
2708 SigEntry::add_entry(obj_int_args.sig(), T_INT);
2709 obj_int_args.compute_calling_conventions();
2710 _obj_int_arg_handler = create_adapter(obj_int_args, true);
2711
2712 CompiledEntrySignature obj_obj_args;
2713 SigEntry::add_entry(obj_obj_args.sig(), T_OBJECT);
2714 SigEntry::add_entry(obj_obj_args.sig(), T_OBJECT);
2715 obj_obj_args.compute_calling_conventions();
2716 _obj_obj_arg_handler = create_adapter(obj_obj_args, true);
2717
2718 // we should always get an entry back but we don't have any
2719 // associated blob on Zero
2720 assert(_no_arg_handler != nullptr &&
2721 _obj_arg_handler != nullptr &&
2722 _int_arg_handler != nullptr &&
2723 _obj_int_arg_handler != nullptr &&
2724 _obj_obj_arg_handler != nullptr, "Initial adapter handlers must be properly created");
2725 }
2726
2727 // Outside of the lock
2728 #ifndef ZERO
2729 // no blobs to register when we are on Zero
2730 post_adapter_creation(_no_arg_handler);
2731 post_adapter_creation(_obj_arg_handler);
2732 post_adapter_creation(_int_arg_handler);
2733 post_adapter_creation(_obj_int_arg_handler);
2734 post_adapter_creation(_obj_obj_arg_handler);
2735 #endif // ZERO
2736 }
2737
2738 AdapterHandlerEntry* AdapterHandlerLibrary::new_entry(AdapterFingerPrint* fingerprint) {
2739 uint id = (uint)AtomicAccess::add((int*)&_id_counter, 1);
2740 assert(id > 0, "we can never overflow because AOT cache cannot contain more than 2^32 methods");
2741 return AdapterHandlerEntry::allocate(id, fingerprint);
2742 }
2743
2744 AdapterHandlerEntry* AdapterHandlerLibrary::get_simple_adapter(const methodHandle& method) {
2745 int total_args_passed = method->size_of_parameters(); // All args on stack
2746 if (total_args_passed == 0) {
2747 return _no_arg_handler;
2748 } else if (total_args_passed == 1) {
2749 if (!method->is_static()) {
2750 if (InlineTypePassFieldsAsArgs && method->method_holder()->is_inline_klass()) {
2751 return nullptr;
2752 }
2753 return _obj_arg_handler;
2754 }
2755 switch (method->signature()->char_at(1)) {
2756 case JVM_SIGNATURE_CLASS: {
2757 if (InlineTypePassFieldsAsArgs) {
2758 SignatureStream ss(method->signature());
2759 InlineKlass* vk = ss.as_inline_klass(method->method_holder());
2760 if (vk != nullptr) {
2761 return nullptr;
2762 }
2763 }
2764 return _obj_arg_handler;
2765 }
2766 case JVM_SIGNATURE_ARRAY:
2767 return _obj_arg_handler;
2768 case JVM_SIGNATURE_INT:
2769 case JVM_SIGNATURE_BOOLEAN:
2770 case JVM_SIGNATURE_CHAR:
2771 case JVM_SIGNATURE_BYTE:
2772 case JVM_SIGNATURE_SHORT:
2773 return _int_arg_handler;
2774 }
2775 } else if (total_args_passed == 2 &&
2776 !method->is_static() && (!InlineTypePassFieldsAsArgs || !method->method_holder()->is_inline_klass())) {
2777 switch (method->signature()->char_at(1)) {
2778 case JVM_SIGNATURE_CLASS: {
2779 if (InlineTypePassFieldsAsArgs) {
2780 SignatureStream ss(method->signature());
2781 InlineKlass* vk = ss.as_inline_klass(method->method_holder());
2782 if (vk != nullptr) {
2783 return nullptr;
2784 }
2785 }
2786 return _obj_obj_arg_handler;
2787 }
2788 case JVM_SIGNATURE_ARRAY:
2789 return _obj_obj_arg_handler;
2790 case JVM_SIGNATURE_INT:
2791 case JVM_SIGNATURE_BOOLEAN:
2792 case JVM_SIGNATURE_CHAR:
2793 case JVM_SIGNATURE_BYTE:
2794 case JVM_SIGNATURE_SHORT:
2795 return _obj_int_arg_handler;
2796 }
2797 }
2798 return nullptr;
2799 }
2800
2801 CompiledEntrySignature::CompiledEntrySignature(Method* method) :
2802 _method(method), _num_inline_args(0), _has_inline_recv(false),
2803 _regs(nullptr), _regs_cc(nullptr), _regs_cc_ro(nullptr),
2804 _args_on_stack(0), _args_on_stack_cc(0), _args_on_stack_cc_ro(0),
2805 _c1_needs_stack_repair(false), _c2_needs_stack_repair(false), _supers(nullptr) {
2806 _sig = new GrowableArray<SigEntry>((method != nullptr) ? method->size_of_parameters() : 1);
2807 _sig_cc = new GrowableArray<SigEntry>((method != nullptr) ? method->size_of_parameters() : 1);
2808 _sig_cc_ro = new GrowableArray<SigEntry>((method != nullptr) ? method->size_of_parameters() : 1);
2809 }
2810
2811 // See if we can save space by sharing the same entry for VIEP and VIEP(RO),
2812 // or the same entry for VEP and VIEP(RO).
2813 CodeOffsets::Entries CompiledEntrySignature::c1_inline_ro_entry_type() const {
2814 if (!has_scalarized_args()) {
2815 // VEP/VIEP/VIEP(RO) all share the same entry. There's no packing.
2816 return CodeOffsets::Verified_Entry;
2817 }
2818 if (_method->is_static()) {
2819 // Static methods don't need VIEP(RO)
2820 return CodeOffsets::Verified_Entry;
2821 }
2822
2823 if (has_inline_recv()) {
2824 if (num_inline_args() == 1) {
2825 // Share same entry for VIEP and VIEP(RO).
2826 // This is quite common: we have an instance method in an InlineKlass that has
2827 // no inline type args other than <this>.
2828 return CodeOffsets::Verified_Inline_Entry;
2829 } else {
2830 assert(num_inline_args() > 1, "must be");
2831 // No sharing:
2832 // VIEP(RO) -- <this> is passed as object
2833 // VEP -- <this> is passed as fields
2834 return CodeOffsets::Verified_Inline_Entry_RO;
2835 }
2836 }
2837
2838 // Either a static method, or <this> is not an inline type
2839 if (args_on_stack_cc() != args_on_stack_cc_ro()) {
2840 // No sharing:
2841 // Some arguments are passed on the stack, and we have inserted reserved entries
2842 // into the VEP, but we never insert reserved entries into the VIEP(RO).
2843 return CodeOffsets::Verified_Inline_Entry_RO;
2844 } else {
2845 // Share same entry for VEP and VIEP(RO).
2846 return CodeOffsets::Verified_Entry;
2847 }
2848 }
2849
2850 // Returns all super methods (transitive) in classes and interfaces that are overridden by the current method.
2851 GrowableArray<Method*>* CompiledEntrySignature::get_supers() {
2852 if (_supers != nullptr) {
2853 return _supers;
2854 }
2855 _supers = new GrowableArray<Method*>();
2856 // Skip private, static, and <init> methods
2857 if (_method->is_private() || _method->is_static() || _method->is_object_constructor()) {
2858 return _supers;
2859 }
2860 Symbol* name = _method->name();
2861 Symbol* signature = _method->signature();
2862 const Klass* holder = _method->method_holder()->super();
2863 Symbol* holder_name = holder->name();
2864 ThreadInVMfromUnknown tiv;
2865 JavaThread* current = JavaThread::current();
2866 HandleMark hm(current);
2867 Handle loader(current, _method->method_holder()->class_loader());
2868
2869 // Walk up the class hierarchy and search for super methods
2870 while (holder != nullptr) {
2871 Method* super_method = holder->lookup_method(name, signature);
2872 if (super_method == nullptr) {
2873 break;
2874 }
2875 if (!super_method->is_static() && !super_method->is_private() &&
2876 (!super_method->is_package_private() ||
2877 super_method->method_holder()->is_same_class_package(loader(), holder_name))) {
2878 _supers->push(super_method);
2879 }
2880 holder = super_method->method_holder()->super();
2881 }
2882 // Search interfaces for super methods
2883 Array<InstanceKlass*>* interfaces = _method->method_holder()->transitive_interfaces();
2884 for (int i = 0; i < interfaces->length(); ++i) {
2885 Method* m = interfaces->at(i)->lookup_method(name, signature);
2886 if (m != nullptr && !m->is_static() && m->is_public()) {
2887 _supers->push(m);
2888 }
2889 }
2890 return _supers;
2891 }
2892
2893 // Iterate over arguments and compute scalarized and non-scalarized signatures
2894 void CompiledEntrySignature::compute_calling_conventions(bool init) {
2895 bool has_scalarized = false;
2896 if (_method != nullptr) {
2897 InstanceKlass* holder = _method->method_holder();
2898 int arg_num = 0;
2899 if (!_method->is_static()) {
2900 // We shouldn't scalarize 'this' in a value class constructor
2901 if (holder->is_inline_klass() && InlineKlass::cast(holder)->can_be_passed_as_fields() && !_method->is_object_constructor() &&
2902 (init || _method->is_scalarized_arg(arg_num))) {
2903 _sig_cc->appendAll(InlineKlass::cast(holder)->extended_sig());
2904 has_scalarized = true;
2905 _has_inline_recv = true;
2906 _num_inline_args++;
2907 } else {
2908 SigEntry::add_entry(_sig_cc, T_OBJECT, holder->name());
2909 }
2910 SigEntry::add_entry(_sig, T_OBJECT, holder->name());
2911 SigEntry::add_entry(_sig_cc_ro, T_OBJECT, holder->name());
2912 arg_num++;
2913 }
2914 for (SignatureStream ss(_method->signature()); !ss.at_return_type(); ss.next()) {
2915 BasicType bt = ss.type();
2916 if (bt == T_OBJECT) {
2917 InlineKlass* vk = ss.as_inline_klass(holder);
2918 if (vk != nullptr && vk->can_be_passed_as_fields() && (init || _method->is_scalarized_arg(arg_num))) {
2919 // Check for a calling convention mismatch with super method(s)
2920 bool scalar_super = false;
2921 bool non_scalar_super = false;
2922 GrowableArray<Method*>* supers = get_supers();
2923 for (int i = 0; i < supers->length(); ++i) {
2924 Method* super_method = supers->at(i);
2925 if (super_method->is_scalarized_arg(arg_num)) {
2926 scalar_super = true;
2927 } else {
2928 non_scalar_super = true;
2929 }
2930 }
2931 #ifdef ASSERT
2932 // Randomly enable below code paths for stress testing
2933 bool stress = init && StressCallingConvention;
2934 if (stress && (os::random() & 1) == 1) {
2935 non_scalar_super = true;
2936 if ((os::random() & 1) == 1) {
2937 scalar_super = true;
2938 }
2939 }
2940 #endif
2941 if (non_scalar_super) {
2942 // Found a super method with a non-scalarized argument. Fall back to the non-scalarized calling convention.
2943 if (scalar_super) {
2944 // Found non-scalar *and* scalar super methods. We can't handle both.
2945 // Mark the scalar method as mismatch and re-compile call sites to use non-scalarized calling convention.
2946 for (int i = 0; i < supers->length(); ++i) {
2947 Method* super_method = supers->at(i);
2948 if (super_method->is_scalarized_arg(arg_num) DEBUG_ONLY(|| (stress && (os::random() & 1) == 1))) {
2949 JavaThread* thread = JavaThread::current();
2950 HandleMark hm(thread);
2951 methodHandle mh(thread, super_method);
2952 DeoptimizationScope deopt_scope;
2953 {
2954 // Keep the lock scope minimal. Prevent interference with other
2955 // dependency checks by setting mismatch and marking within the lock.
2956 MutexLocker ml(Compile_lock, Mutex::_safepoint_check_flag);
2957 super_method->set_mismatch();
2958 CodeCache::mark_for_deoptimization(&deopt_scope, mh());
2959 }
2960 deopt_scope.deoptimize_marked();
2961 }
2962 }
2963 }
2964 // Fall back to non-scalarized calling convention
2965 SigEntry::add_entry(_sig_cc, T_OBJECT, ss.as_symbol());
2966 SigEntry::add_entry(_sig_cc_ro, T_OBJECT, ss.as_symbol());
2967 } else {
2968 _num_inline_args++;
2969 has_scalarized = true;
2970 int last = _sig_cc->length();
2971 int last_ro = _sig_cc_ro->length();
2972 _sig_cc->appendAll(vk->extended_sig());
2973 _sig_cc_ro->appendAll(vk->extended_sig());
2974 // Insert InlineTypeNode::NullMarker field right after T_METADATA delimiter
2975 _sig_cc->insert_before(last+1, SigEntry(T_BOOLEAN, -1, nullptr, true));
2976 _sig_cc_ro->insert_before(last_ro+1, SigEntry(T_BOOLEAN, -1, nullptr, true));
2977 }
2978 } else {
2979 SigEntry::add_entry(_sig_cc, T_OBJECT, ss.as_symbol());
2980 SigEntry::add_entry(_sig_cc_ro, T_OBJECT, ss.as_symbol());
2981 }
2982 bt = T_OBJECT;
2983 } else {
2984 SigEntry::add_entry(_sig_cc, ss.type(), ss.as_symbol());
2985 SigEntry::add_entry(_sig_cc_ro, ss.type(), ss.as_symbol());
2986 }
2987 SigEntry::add_entry(_sig, bt, ss.as_symbol());
2988 if (bt != T_VOID) {
2989 arg_num++;
2990 }
2991 }
2992 }
2993
2994 // Compute the non-scalarized calling convention
2995 _regs = NEW_RESOURCE_ARRAY(VMRegPair, _sig->length());
2996 _args_on_stack = SharedRuntime::java_calling_convention(_sig, _regs);
2997
2998 // Compute the scalarized calling conventions if there are scalarized inline types in the signature
2999 if (has_scalarized && !_method->is_native()) {
3000 _regs_cc = NEW_RESOURCE_ARRAY(VMRegPair, _sig_cc->length());
3001 _args_on_stack_cc = SharedRuntime::java_calling_convention(_sig_cc, _regs_cc);
3002
3003 _regs_cc_ro = NEW_RESOURCE_ARRAY(VMRegPair, _sig_cc_ro->length());
3004 _args_on_stack_cc_ro = SharedRuntime::java_calling_convention(_sig_cc_ro, _regs_cc_ro);
3005
3006 _c1_needs_stack_repair = (_args_on_stack_cc < _args_on_stack) || (_args_on_stack_cc_ro < _args_on_stack);
3007 _c2_needs_stack_repair = (_args_on_stack_cc > _args_on_stack) || (_args_on_stack_cc > _args_on_stack_cc_ro);
3008
3009 // Upper bound on stack arguments to avoid hitting the argument limit and
3010 // bailing out of compilation ("unsupported incoming calling sequence").
3011 // TODO we need a reasonable limit (flag?) here
3012 if (MAX2(_args_on_stack_cc, _args_on_stack_cc_ro) <= 60) {
3013 return; // Success
3014 }
3015 }
3016
3017 // No scalarized args
3018 _sig_cc = _sig;
3019 _regs_cc = _regs;
3020 _args_on_stack_cc = _args_on_stack;
3021
3022 _sig_cc_ro = _sig;
3023 _regs_cc_ro = _regs;
3024 _args_on_stack_cc_ro = _args_on_stack;
3025 }
3026
3027 void CompiledEntrySignature::initialize_from_fingerprint(AdapterFingerPrint* fingerprint) {
3028 _has_inline_recv = fingerprint->has_ro_adapter();
3029
3030 int value_object_count = 0;
3031 BasicType prev_bt = T_ILLEGAL;
3032 bool has_scalarized_arguments = false;
3033 bool long_prev = false;
3034 int long_prev_offset = -1;
3035
3036 fingerprint->iterate_args([&] (const AdapterFingerPrint::Element& arg) {
3037 BasicType bt = arg.bt();
3038 int offset = arg.offset();
3039
3040 if (long_prev) {
3041 long_prev = false;
3042 BasicType bt_to_add;
3043 if (bt == T_VOID) {
3044 bt_to_add = T_LONG;
3045 } else {
3046 bt_to_add = T_OBJECT;
3047 }
3048 if (value_object_count == 0) {
3049 SigEntry::add_entry(_sig, bt_to_add);
3050 }
3051 SigEntry::add_entry(_sig_cc, bt_to_add, nullptr, long_prev_offset);
3052 SigEntry::add_entry(_sig_cc_ro, bt_to_add, nullptr, long_prev_offset);
3053 }
3054
3055 switch (bt) {
3056 case T_VOID:
3057 if (prev_bt != T_LONG && prev_bt != T_DOUBLE) {
3058 assert(InlineTypePassFieldsAsArgs, "unexpected end of inline type");
3059 value_object_count--;
3060 SigEntry::add_entry(_sig_cc, T_VOID, nullptr, offset);
3061 SigEntry::add_entry(_sig_cc_ro, T_VOID, nullptr, offset);
3062 assert(value_object_count >= 0, "invalid value object count");
3063 } else {
3064 // Nothing to add for _sig: We already added an addition T_VOID in add_entry() when adding T_LONG or T_DOUBLE.
3065 }
3066 break;
3067 case T_INT:
3068 case T_FLOAT:
3069 case T_DOUBLE:
3070 if (value_object_count == 0) {
3071 SigEntry::add_entry(_sig, bt);
3072 }
3073 SigEntry::add_entry(_sig_cc, bt, nullptr, offset);
3074 SigEntry::add_entry(_sig_cc_ro, bt, nullptr, offset);
3075 break;
3076 case T_LONG:
3077 long_prev = true;
3078 long_prev_offset = offset;
3079 break;
3080 case T_BOOLEAN:
3081 case T_CHAR:
3082 case T_BYTE:
3083 case T_SHORT:
3084 case T_OBJECT:
3085 case T_ARRAY:
3086 assert(value_object_count > 0, "must be value object field");
3087 SigEntry::add_entry(_sig_cc, bt, nullptr, offset);
3088 SigEntry::add_entry(_sig_cc_ro, bt, nullptr, offset);
3089 break;
3090 case T_METADATA:
3091 assert(InlineTypePassFieldsAsArgs, "unexpected start of inline type");
3092 if (value_object_count == 0) {
3093 SigEntry::add_entry(_sig, T_OBJECT);
3094 }
3095 SigEntry::add_entry(_sig_cc, T_METADATA, nullptr, offset);
3096 SigEntry::add_entry(_sig_cc_ro, T_METADATA, nullptr, offset);
3097 value_object_count++;
3098 has_scalarized_arguments = true;
3099 break;
3100 default: {
3101 fatal("Unexpected BasicType: %s", basictype_to_str(bt));
3102 }
3103 }
3104 prev_bt = bt;
3105 });
3106
3107 if (long_prev) {
3108 // If previous bt was T_LONG and we reached the end of the signature, we know that it must be a T_OBJECT.
3109 SigEntry::add_entry(_sig, T_OBJECT);
3110 SigEntry::add_entry(_sig_cc, T_OBJECT);
3111 SigEntry::add_entry(_sig_cc_ro, T_OBJECT);
3112 }
3113 assert(value_object_count == 0, "invalid value object count");
3114
3115 _regs = NEW_RESOURCE_ARRAY(VMRegPair, _sig->length());
3116 _args_on_stack = SharedRuntime::java_calling_convention(_sig, _regs);
3117
3118 // Compute the scalarized calling conventions if there are scalarized inline types in the signature
3119 if (has_scalarized_arguments) {
3120 _regs_cc = NEW_RESOURCE_ARRAY(VMRegPair, _sig_cc->length());
3121 _args_on_stack_cc = SharedRuntime::java_calling_convention(_sig_cc, _regs_cc);
3122
3123 _regs_cc_ro = NEW_RESOURCE_ARRAY(VMRegPair, _sig_cc_ro->length());
3124 _args_on_stack_cc_ro = SharedRuntime::java_calling_convention(_sig_cc_ro, _regs_cc_ro);
3125
3126 _c1_needs_stack_repair = (_args_on_stack_cc < _args_on_stack) || (_args_on_stack_cc_ro < _args_on_stack);
3127 _c2_needs_stack_repair = (_args_on_stack_cc > _args_on_stack) || (_args_on_stack_cc > _args_on_stack_cc_ro);
3128 } else {
3129 // No scalarized args
3130 _sig_cc = _sig;
3131 _regs_cc = _regs;
3132 _args_on_stack_cc = _args_on_stack;
3133
3134 _sig_cc_ro = _sig;
3135 _regs_cc_ro = _regs;
3136 _args_on_stack_cc_ro = _args_on_stack;
3137 }
3138
3139 #ifdef ASSERT
3140 {
3141 AdapterFingerPrint* compare_fp = AdapterFingerPrint::allocate(_sig_cc, _has_inline_recv);
3142 assert(fingerprint->equals(compare_fp), "%s - %s", fingerprint->as_string(), compare_fp->as_string());
3143 AdapterFingerPrint::deallocate(compare_fp);
3144 }
3145 #endif
3146 }
3147
3148 const char* AdapterHandlerEntry::_entry_names[] = {
3149 "i2c", "c2i", "c2i_unverified", "c2i_no_clinit_check"
3150 };
3151
3152 #ifdef ASSERT
3153 void AdapterHandlerLibrary::verify_adapter_sharing(CompiledEntrySignature& ces, AdapterHandlerEntry* cached_entry) {
3154 // we can only check for the same code if there is any
3155 #ifndef ZERO
3156 AdapterHandlerEntry* comparison_entry = create_adapter(ces, false, true);
3157 assert(comparison_entry->adapter_blob() == nullptr, "no blob should be created when creating an adapter for comparison");
3158 assert(comparison_entry->compare_code(cached_entry), "code must match");
3159 // Release the one just created
3160 AdapterHandlerEntry::deallocate(comparison_entry);
3161 # endif // ZERO
3162 }
3163 #endif /* ASSERT*/
3164
3165 AdapterHandlerEntry* AdapterHandlerLibrary::get_adapter(const methodHandle& method) {
3166 assert(!method->is_abstract(), "abstract methods do not have adapters");
3167 // Use customized signature handler. Need to lock around updates to
3168 // the _adapter_handler_table (it is not safe for concurrent readers
3169 // and a single writer: this could be fixed if it becomes a
3170 // problem).
3171
3172 // Fast-path for trivial adapters
3173 AdapterHandlerEntry* entry = get_simple_adapter(method);
3174 if (entry != nullptr) {
3175 return entry;
3176 }
3177
3178 ResourceMark rm;
3179 bool new_entry = false;
3180
3181 CompiledEntrySignature ces(method());
3182 ces.compute_calling_conventions();
3183 if (ces.has_scalarized_args()) {
3184 if (!method->has_scalarized_args()) {
3185 method->set_has_scalarized_args();
3186 }
3187 if (ces.c1_needs_stack_repair()) {
3188 method->set_c1_needs_stack_repair();
3189 }
3190 if (ces.c2_needs_stack_repair() && !method->c2_needs_stack_repair()) {
3191 method->set_c2_needs_stack_repair();
3192 }
3193 }
3194
3195 {
3196 MutexLocker mu(AdapterHandlerLibrary_lock);
3197
3198 // Lookup method signature's fingerprint
3199 entry = lookup(ces.sig_cc(), ces.has_inline_recv());
3200
3201 if (entry != nullptr) {
3202 #ifndef ZERO
3203 assert(entry->is_linked(), "AdapterHandlerEntry must have been linked");
3204 #endif
3205 #ifdef ASSERT
3206 if (!entry->in_aot_cache() && VerifyAdapterSharing) {
3207 verify_adapter_sharing(ces, entry);
3208 }
3209 #endif
3210 } else {
3211 entry = create_adapter(ces, /* allocate_code_blob */ true);
3212 if (entry != nullptr) {
3213 new_entry = true;
3214 }
3215 }
3216 }
3217
3218 // Outside of the lock
3219 if (new_entry) {
3220 post_adapter_creation(entry);
3221 }
3222 return entry;
3223 }
3224
3225 void AdapterHandlerLibrary::lookup_aot_cache(AdapterHandlerEntry* handler) {
3226 ResourceMark rm;
3227 const char* name = AdapterHandlerLibrary::name(handler);
3228 const uint32_t id = AdapterHandlerLibrary::id(handler);
3229
3230 CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::Adapter, id, name);
3231 if (blob != nullptr) {
3232 handler->set_adapter_blob(blob->as_adapter_blob());
3233 }
3234 }
3235
3236 #ifndef PRODUCT
3237 void AdapterHandlerLibrary::print_adapter_handler_info(outputStream* st, AdapterHandlerEntry* handler) {
3238 ttyLocker ttyl;
3239 ResourceMark rm;
3240 int insts_size;
3241 // on Zero the blob may be null
3242 handler->print_adapter_on(tty);
3243 AdapterBlob* adapter_blob = handler->adapter_blob();
3244 if (adapter_blob == nullptr) {
3245 return;
3246 }
3247 insts_size = adapter_blob->code_size();
3248 st->print_cr("i2c argument handler for: %s %s (%d bytes generated)",
3249 handler->fingerprint()->as_basic_args_string(),
3250 handler->fingerprint()->as_string(), insts_size);
3251 st->print_cr("c2i argument handler starts at " INTPTR_FORMAT, p2i(handler->get_c2i_entry()));
3252 if (Verbose || PrintStubCode) {
3253 address first_pc = adapter_blob->content_begin();
3254 if (first_pc != nullptr) {
3255 Disassembler::decode(first_pc, first_pc + insts_size, st, &adapter_blob->asm_remarks());
3256 st->cr();
3257 }
3258 }
3259 }
3260 #endif // PRODUCT
3261
3262 void AdapterHandlerLibrary::address_to_offset(address entry_address[AdapterBlob::ENTRY_COUNT],
3263 int entry_offset[AdapterBlob::ENTRY_COUNT]) {
3264 entry_offset[AdapterBlob::I2C] = 0;
3265 entry_offset[AdapterBlob::C2I] = entry_address[AdapterBlob::C2I] - entry_address[AdapterBlob::I2C];
3266 entry_offset[AdapterBlob::C2I_Inline] = entry_address[AdapterBlob::C2I_Inline] - entry_address[AdapterBlob::I2C];
3267 entry_offset[AdapterBlob::C2I_Inline_RO] = entry_address[AdapterBlob::C2I_Inline_RO] - entry_address[AdapterBlob::I2C];
3268 entry_offset[AdapterBlob::C2I_Unverified] = entry_address[AdapterBlob::C2I_Unverified] - entry_address[AdapterBlob::I2C];
3269 entry_offset[AdapterBlob::C2I_Unverified_Inline] = entry_address[AdapterBlob::C2I_Unverified_Inline] - entry_address[AdapterBlob::I2C];
3270 if (entry_address[AdapterBlob::C2I_No_Clinit_Check] == nullptr) {
3271 entry_offset[AdapterBlob::C2I_No_Clinit_Check] = -1;
3272 } else {
3273 entry_offset[AdapterBlob::C2I_No_Clinit_Check] = entry_address[AdapterBlob::C2I_No_Clinit_Check] - entry_address[AdapterBlob::I2C];
3274 }
3275 }
3276
3277 bool AdapterHandlerLibrary::generate_adapter_code(AdapterHandlerEntry* handler,
3278 CompiledEntrySignature& ces,
3279 bool allocate_code_blob,
3280 bool is_transient) {
3281 if (log_is_enabled(Info, perf, class, link)) {
3282 ClassLoader::perf_method_adapters_count()->inc();
3283 }
3284
3285 #ifndef ZERO
3286 AdapterBlob* adapter_blob = nullptr;
3287 BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache
3288 CodeBuffer buffer(buf);
3289 short buffer_locs[20];
3290 buffer.insts()->initialize_shared_locs((relocInfo*)buffer_locs,
3291 sizeof(buffer_locs)/sizeof(relocInfo));
3292 MacroAssembler masm(&buffer);
3293 address entry_address[AdapterBlob::ENTRY_COUNT];
3294
3295 // Get a description of the compiled java calling convention and the largest used (VMReg) stack slot usage
3296 SharedRuntime::generate_i2c2i_adapters(&masm,
3297 ces.args_on_stack(),
3298 ces.sig(),
3299 ces.regs(),
3300 ces.sig_cc(),
3301 ces.regs_cc(),
3302 ces.sig_cc_ro(),
3303 ces.regs_cc_ro(),
3304 entry_address,
3305 adapter_blob,
3306 allocate_code_blob);
3307
3308 if (ces.has_scalarized_args()) {
3309 // Save a C heap allocated version of the scalarized signature and store it in the adapter
3310 GrowableArray<SigEntry>* heap_sig = new (mtInternal) GrowableArray<SigEntry>(ces.sig_cc()->length(), mtInternal);
3311 heap_sig->appendAll(ces.sig_cc());
3312 handler->set_sig_cc(heap_sig);
3313 }
3314 // On zero there is no code to save and no need to create a blob and
3315 // or relocate the handler.
3316 int entry_offset[AdapterBlob::ENTRY_COUNT];
3317 address_to_offset(entry_address, entry_offset);
3318 #ifdef ASSERT
3319 if (VerifyAdapterSharing) {
3320 handler->save_code(buf->code_begin(), buffer.insts_size());
3321 if (is_transient) {
3322 return true;
3323 }
3324 }
3325 #endif
3326 if (adapter_blob == nullptr) {
3327 // CodeCache is full, disable compilation
3328 // Ought to log this but compile log is only per compile thread
3329 // and we're some non descript Java thread.
3330 return false;
3331 }
3332 handler->set_adapter_blob(adapter_blob);
3333 if (!is_transient && AOTCodeCache::is_dumping_adapter()) {
3334 // try to save generated code
3335 const char* name = AdapterHandlerLibrary::name(handler);
3336 const uint32_t id = AdapterHandlerLibrary::id(handler);
3337 bool success = AOTCodeCache::store_code_blob(*adapter_blob, AOTCodeEntry::Adapter, id, name);
3338 assert(success || !AOTCodeCache::is_dumping_adapter(), "caching of adapter must be disabled");
3339 }
3340 #endif // ZERO
3341
3342 #ifndef PRODUCT
3343 // debugging support
3344 if (PrintAdapterHandlers || PrintStubCode) {
3345 print_adapter_handler_info(tty, handler);
3346 }
3347 #endif
3348
3349 return true;
3350 }
3351
3352 AdapterHandlerEntry* AdapterHandlerLibrary::create_adapter(CompiledEntrySignature& ces,
3353 bool allocate_code_blob,
3354 bool is_transient) {
3355 AdapterFingerPrint* fp = AdapterFingerPrint::allocate(ces.sig_cc(), ces.has_inline_recv());
3356 #ifdef ASSERT
3357 // Verify that we can successfully restore the compiled entry signature object.
3358 CompiledEntrySignature ces_verify;
3359 ces_verify.initialize_from_fingerprint(fp);
3360 #endif
3361 AdapterHandlerEntry* handler = AdapterHandlerLibrary::new_entry(fp);
3362 if (!generate_adapter_code(handler, ces, allocate_code_blob, is_transient)) {
3363 AdapterHandlerEntry::deallocate(handler);
3364 return nullptr;
3365 }
3366 if (!is_transient) {
3367 assert_lock_strong(AdapterHandlerLibrary_lock);
3368 _adapter_handler_table->put(fp, handler);
3369 }
3370 return handler;
3371 }
3372
3373 #if INCLUDE_CDS
3374 void AdapterHandlerEntry::remove_unshareable_info() {
3375 #ifdef ASSERT
3376 _saved_code = nullptr;
3377 _saved_code_length = 0;
3378 #endif // ASSERT
3379 _adapter_blob = nullptr;
3380 _linked = false;
3381 _sig_cc = nullptr;
3382 }
3383
3384 class CopyAdapterTableToArchive : StackObj {
3385 private:
3386 CompactHashtableWriter* _writer;
3387 ArchiveBuilder* _builder;
3388 public:
3389 CopyAdapterTableToArchive(CompactHashtableWriter* writer) : _writer(writer),
3390 _builder(ArchiveBuilder::current())
3391 {}
3392
3393 bool do_entry(AdapterFingerPrint* fp, AdapterHandlerEntry* entry) {
3394 LogStreamHandle(Trace, aot) lsh;
3395 if (ArchiveBuilder::current()->has_been_archived((address)entry)) {
3396 assert(ArchiveBuilder::current()->has_been_archived((address)fp), "must be");
3397 AdapterFingerPrint* buffered_fp = ArchiveBuilder::current()->get_buffered_addr(fp);
3398 assert(buffered_fp != nullptr,"sanity check");
3399 AdapterHandlerEntry* buffered_entry = ArchiveBuilder::current()->get_buffered_addr(entry);
3400 assert(buffered_entry != nullptr,"sanity check");
3401
3402 uint hash = fp->compute_hash();
3403 _writer->add(hash, AOTCompressedPointers::encode_not_null(buffered_entry));
3404 if (lsh.is_enabled()) {
3405 address fp_runtime_addr = (address)buffered_fp + ArchiveBuilder::current()->buffer_to_requested_delta();
3406 address entry_runtime_addr = (address)buffered_entry + ArchiveBuilder::current()->buffer_to_requested_delta();
3407 log_trace(aot)("Added fp=%p (%s), entry=%p to the archived adater table", buffered_fp, buffered_fp->as_basic_args_string(), buffered_entry);
3408 }
3409 } else {
3410 if (lsh.is_enabled()) {
3411 log_trace(aot)("Skipping adapter handler %p (fp=%s) as it is not archived", entry, fp->as_basic_args_string());
3412 }
3413 }
3414 return true;
3415 }
3416 };
3417
3418 void AdapterHandlerLibrary::dump_aot_adapter_table() {
3419 CompactHashtableStats stats;
3420 CompactHashtableWriter writer(_adapter_handler_table->number_of_entries(), &stats);
3421 CopyAdapterTableToArchive copy(&writer);
3422 _adapter_handler_table->iterate(©);
3423 writer.dump(&_aot_adapter_handler_table, "archived adapter table");
3424 }
3425
3426 void AdapterHandlerLibrary::serialize_shared_table_header(SerializeClosure* soc) {
3427 _aot_adapter_handler_table.serialize_header(soc);
3428 }
3429
3430 void AdapterHandlerLibrary::link_aot_adapter_handler(AdapterHandlerEntry* handler) {
3431 #ifdef ASSERT
3432 if (TestAOTAdapterLinkFailure) {
3433 return;
3434 }
3435 #endif
3436 lookup_aot_cache(handler);
3437 #ifndef PRODUCT
3438 // debugging support
3439 if (PrintAdapterHandlers || PrintStubCode) {
3440 print_adapter_handler_info(tty, handler);
3441 }
3442 #endif
3443 }
3444
3445 // This method is used during production run to link archived adapters (stored in AOT Cache)
3446 // to their code in AOT Code Cache
3447 void AdapterHandlerEntry::link() {
3448 ResourceMark rm;
3449 assert(_fingerprint != nullptr, "_fingerprint must not be null");
3450 bool generate_code = false;
3451 // Generate code only if AOTCodeCache is not available, or
3452 // caching adapters is disabled, or we fail to link
3453 // the AdapterHandlerEntry to its code in the AOTCodeCache
3454 if (AOTCodeCache::is_using_adapter()) {
3455 AdapterHandlerLibrary::link_aot_adapter_handler(this);
3456 // If link_aot_adapter_handler() succeeds, _adapter_blob will be non-null
3457 if (_adapter_blob == nullptr) {
3458 log_warning(aot)("Failed to link AdapterHandlerEntry (fp=%s) to its code in the AOT code cache", _fingerprint->as_basic_args_string());
3459 generate_code = true;
3460 }
3461
3462 if (get_sig_cc() == nullptr) {
3463 // Calling conventions have to be regenerated at runtime and are accessed through method adapters,
3464 // which are archived in the AOT code cache. If the adapters are not regenerated, the
3465 // calling conventions should be regenerated here.
3466 CompiledEntrySignature ces;
3467 ces.initialize_from_fingerprint(_fingerprint);
3468 if (ces.has_scalarized_args()) {
3469 // Save a C heap allocated version of the scalarized signature and store it in the adapter
3470 GrowableArray<SigEntry>* heap_sig = new (mtInternal) GrowableArray<SigEntry>(ces.sig_cc()->length(), mtInternal);
3471 heap_sig->appendAll(ces.sig_cc());
3472 set_sig_cc(heap_sig);
3473 }
3474 }
3475 } else {
3476 generate_code = true;
3477 }
3478
3479 if (generate_code) {
3480 CompiledEntrySignature ces;
3481 ces.initialize_from_fingerprint(_fingerprint);
3482 if (!AdapterHandlerLibrary::generate_adapter_code(this, ces, true, false)) {
3483 // Don't throw exceptions during VM initialization because java.lang.* classes
3484 // might not have been initialized, causing problems when constructing the
3485 // Java exception object.
3486 vm_exit_during_initialization("Out of space in CodeCache for adapters");
3487 }
3488 }
3489 if (_adapter_blob != nullptr) {
3490 post_adapter_creation(this);
3491 }
3492 assert(_linked, "AdapterHandlerEntry must now be linked");
3493 }
3494
3495 void AdapterHandlerLibrary::link_aot_adapters() {
3496 uint max_id = 0;
3497 assert(AOTCodeCache::is_using_adapter(), "AOT adapters code should be available");
3498 /* It is possible that some adapters generated in assembly phase are not stored in the cache.
3499 * That implies adapter ids of the adapters in the cache may not be contiguous.
3500 * If the size of the _aot_adapter_handler_table is used to initialize _id_counter, then it may
3501 * result in collision of adapter ids between AOT stored handlers and runtime generated handlers.
3502 * To avoid such situation, initialize the _id_counter with the largest adapter id among the AOT stored handlers.
3503 */
3504 _aot_adapter_handler_table.iterate_all([&](AdapterHandlerEntry* entry) {
3505 assert(!entry->is_linked(), "AdapterHandlerEntry is already linked!");
3506 entry->link();
3507 max_id = MAX2(max_id, entry->id());
3508 });
3509 // Set adapter id to the maximum id found in the AOTCache
3510 assert(_id_counter == 0, "Did not expect new AdapterHandlerEntry to be created at this stage");
3511 _id_counter = max_id;
3512 }
3513
3514 // This method is called during production run to lookup simple adapters
3515 // in the archived adapter handler table
3516 void AdapterHandlerLibrary::lookup_simple_adapters() {
3517 assert(!_aot_adapter_handler_table.empty(), "archived adapter handler table is empty");
3518
3519 MutexLocker mu(AdapterHandlerLibrary_lock);
3520 ResourceMark rm;
3521 CompiledEntrySignature no_args;
3522 no_args.compute_calling_conventions();
3523 _no_arg_handler = lookup(no_args.sig_cc(), no_args.has_inline_recv());
3524
3525 CompiledEntrySignature obj_args;
3526 SigEntry::add_entry(obj_args.sig(), T_OBJECT);
3527 obj_args.compute_calling_conventions();
3528 _obj_arg_handler = lookup(obj_args.sig_cc(), obj_args.has_inline_recv());
3529
3530 CompiledEntrySignature int_args;
3531 SigEntry::add_entry(int_args.sig(), T_INT);
3532 int_args.compute_calling_conventions();
3533 _int_arg_handler = lookup(int_args.sig_cc(), int_args.has_inline_recv());
3534
3535 CompiledEntrySignature obj_int_args;
3536 SigEntry::add_entry(obj_int_args.sig(), T_OBJECT);
3537 SigEntry::add_entry(obj_int_args.sig(), T_INT);
3538 obj_int_args.compute_calling_conventions();
3539 _obj_int_arg_handler = lookup(obj_int_args.sig_cc(), obj_int_args.has_inline_recv());
3540
3541 CompiledEntrySignature obj_obj_args;
3542 SigEntry::add_entry(obj_obj_args.sig(), T_OBJECT);
3543 SigEntry::add_entry(obj_obj_args.sig(), T_OBJECT);
3544 obj_obj_args.compute_calling_conventions();
3545 _obj_obj_arg_handler = lookup(obj_obj_args.sig_cc(), obj_obj_args.has_inline_recv());
3546
3547 assert(_no_arg_handler != nullptr &&
3548 _obj_arg_handler != nullptr &&
3549 _int_arg_handler != nullptr &&
3550 _obj_int_arg_handler != nullptr &&
3551 _obj_obj_arg_handler != nullptr, "Initial adapters not found in archived adapter handler table");
3552 assert(_no_arg_handler->is_linked() &&
3553 _obj_arg_handler->is_linked() &&
3554 _int_arg_handler->is_linked() &&
3555 _obj_int_arg_handler->is_linked() &&
3556 _obj_obj_arg_handler->is_linked(), "Initial adapters not in linked state");
3557 }
3558 #endif // INCLUDE_CDS
3559
3560 void AdapterHandlerEntry::metaspace_pointers_do(MetaspaceClosure* it) {
3561 LogStreamHandle(Trace, aot) lsh;
3562 if (lsh.is_enabled()) {
3563 lsh.print("Iter(AdapterHandlerEntry): %p(%s)", this, _fingerprint->as_basic_args_string());
3564 lsh.cr();
3565 }
3566 it->push(&_fingerprint);
3567 }
3568
3569 AdapterHandlerEntry::~AdapterHandlerEntry() {
3570 if (_fingerprint != nullptr) {
3571 AdapterFingerPrint::deallocate(_fingerprint);
3572 _fingerprint = nullptr;
3573 }
3574 if (_sig_cc != nullptr) {
3575 delete _sig_cc;
3576 }
3577 #ifdef ASSERT
3578 FREE_C_HEAP_ARRAY(unsigned char, _saved_code);
3579 #endif
3580 FreeHeap(this);
3581 }
3582
3583
3584 #ifdef ASSERT
3585 // Capture the code before relocation so that it can be compared
3586 // against other versions. If the code is captured after relocation
3587 // then relative instructions won't be equivalent.
3588 void AdapterHandlerEntry::save_code(unsigned char* buffer, int length) {
3589 _saved_code = NEW_C_HEAP_ARRAY(unsigned char, length, mtCode);
3590 _saved_code_length = length;
3591 memcpy(_saved_code, buffer, length);
3592 }
3593
3594
3595 bool AdapterHandlerEntry::compare_code(AdapterHandlerEntry* other) {
3596 assert(_saved_code != nullptr && other->_saved_code != nullptr, "code not saved");
3597
3598 if (other->_saved_code_length != _saved_code_length) {
3599 return false;
3600 }
3601
3602 return memcmp(other->_saved_code, _saved_code, _saved_code_length) == 0;
3603 }
3604 #endif
3605
3606
3607 /**
3608 * Create a native wrapper for this native method. The wrapper converts the
3609 * Java-compiled calling convention to the native convention, handles
3610 * arguments, and transitions to native. On return from the native we transition
3611 * back to java blocking if a safepoint is in progress.
3612 */
3613 void AdapterHandlerLibrary::create_native_wrapper(const methodHandle& method) {
3614 ResourceMark rm;
3615 nmethod* nm = nullptr;
3616
3617 // Check if memory should be freed before allocation
3618 CodeCache::gc_on_allocation();
3619
3620 assert(method->is_native(), "must be native");
3621 assert(method->is_special_native_intrinsic() ||
3622 method->has_native_function(), "must have something valid to call!");
3623
3624 {
3625 // Perform the work while holding the lock, but perform any printing outside the lock
3626 MutexLocker mu(AdapterHandlerLibrary_lock);
3627 // See if somebody beat us to it
3628 if (method->code() != nullptr) {
3629 return;
3630 }
3631
3632 const int compile_id = CompileBroker::assign_compile_id(method, CompileBroker::standard_entry_bci);
3633 assert(compile_id > 0, "Must generate native wrapper");
3634
3635
3636 ResourceMark rm;
3637 BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache
3638 if (buf != nullptr) {
3639 CodeBuffer buffer(buf);
3640
3641 if (method->is_continuation_enter_intrinsic()) {
3642 buffer.initialize_stubs_size(192);
3643 }
3644
3645 struct { double data[20]; } locs_buf;
3646 struct { double data[20]; } stubs_locs_buf;
3647 buffer.insts()->initialize_shared_locs((relocInfo*)&locs_buf, sizeof(locs_buf) / sizeof(relocInfo));
3648 #if defined(AARCH64) || defined(PPC64)
3649 // On AArch64 with ZGC and nmethod entry barriers, we need all oops to be
3650 // in the constant pool to ensure ordering between the barrier and oops
3651 // accesses. For native_wrappers we need a constant.
3652 // On PPC64 the continuation enter intrinsic needs the constant pool for the compiled
3653 // static java call that is resolved in the runtime.
3654 if (PPC64_ONLY(method->is_continuation_enter_intrinsic() &&) true) {
3655 buffer.initialize_consts_size(8 PPC64_ONLY(+ 24));
3656 }
3657 #endif
3658 buffer.stubs()->initialize_shared_locs((relocInfo*)&stubs_locs_buf, sizeof(stubs_locs_buf) / sizeof(relocInfo));
3659 MacroAssembler _masm(&buffer);
3660
3661 // Fill in the signature array, for the calling-convention call.
3662 const int total_args_passed = method->size_of_parameters();
3663
3664 BasicType stack_sig_bt[16];
3665 VMRegPair stack_regs[16];
3666 BasicType* sig_bt = (total_args_passed <= 16) ? stack_sig_bt : NEW_RESOURCE_ARRAY(BasicType, total_args_passed);
3667 VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
3668
3669 int i = 0;
3670 if (!method->is_static()) { // Pass in receiver first
3671 sig_bt[i++] = T_OBJECT;
3672 }
3673 SignatureStream ss(method->signature());
3674 for (; !ss.at_return_type(); ss.next()) {
3675 sig_bt[i++] = ss.type(); // Collect remaining bits of signature
3676 if (ss.type() == T_LONG || ss.type() == T_DOUBLE) {
3677 sig_bt[i++] = T_VOID; // Longs & doubles take 2 Java slots
3678 }
3679 }
3680 assert(i == total_args_passed, "");
3681 BasicType ret_type = ss.type();
3682
3683 // Now get the compiled-Java arguments layout.
3684 SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed);
3685
3686 // Generate the compiled-to-native wrapper code
3687 nm = SharedRuntime::generate_native_wrapper(&_masm, method, compile_id, sig_bt, regs, ret_type);
3688
3689 if (nm != nullptr) {
3690 {
3691 MutexLocker pl(NMethodState_lock, Mutex::_no_safepoint_check_flag);
3692 if (nm->make_in_use()) {
3693 method->set_code(method, nm);
3694 }
3695 }
3696
3697 DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, CompileBroker::compiler(CompLevel_simple));
3698 if (directive->PrintAssemblyOption) {
3699 nm->print_code();
3700 }
3701 DirectivesStack::release(directive);
3702 }
3703 }
3704 } // Unlock AdapterHandlerLibrary_lock
3705
3706
3707 // Install the generated code.
3708 if (nm != nullptr) {
3709 const char *msg = method->is_static() ? "(static)" : "";
3710 CompileTask::print_ul(nm, msg);
3711 if (PrintCompilation) {
3712 ttyLocker ttyl;
3713 CompileTask::print(tty, nm, msg);
3714 }
3715 nm->post_compiled_method_load_event();
3716 }
3717 }
3718
3719 // -------------------------------------------------------------------------
3720 // Java-Java calling convention
3721 // (what you use when Java calls Java)
3722
3723 //------------------------------name_for_receiver----------------------------------
3724 // For a given signature, return the VMReg for parameter 0.
3725 VMReg SharedRuntime::name_for_receiver() {
3726 VMRegPair regs;
3727 BasicType sig_bt = T_OBJECT;
3728 (void) java_calling_convention(&sig_bt, ®s, 1);
3729 // Return argument 0 register. In the LP64 build pointers
3730 // take 2 registers, but the VM wants only the 'main' name.
3731 return regs.first();
3732 }
3733
3734 VMRegPair *SharedRuntime::find_callee_arguments(Symbol* sig, bool has_receiver, bool has_appendix, int* arg_size) {
3735 // This method is returning a data structure allocating as a
3736 // ResourceObject, so do not put any ResourceMarks in here.
3737
3738 BasicType *sig_bt = NEW_RESOURCE_ARRAY(BasicType, 256);
3739 VMRegPair *regs = NEW_RESOURCE_ARRAY(VMRegPair, 256);
3740 int cnt = 0;
3741 if (has_receiver) {
3742 sig_bt[cnt++] = T_OBJECT; // Receiver is argument 0; not in signature
3743 }
3744
3745 for (SignatureStream ss(sig); !ss.at_return_type(); ss.next()) {
3746 BasicType type = ss.type();
3747 sig_bt[cnt++] = type;
3748 if (is_double_word_type(type))
3749 sig_bt[cnt++] = T_VOID;
3750 }
3751
3752 if (has_appendix) {
3753 sig_bt[cnt++] = T_OBJECT;
3754 }
3755
3756 assert(cnt < 256, "grow table size");
3757
3758 int comp_args_on_stack;
3759 comp_args_on_stack = java_calling_convention(sig_bt, regs, cnt);
3760
3761 // the calling convention doesn't count out_preserve_stack_slots so
3762 // we must add that in to get "true" stack offsets.
3763
3764 if (comp_args_on_stack) {
3765 for (int i = 0; i < cnt; i++) {
3766 VMReg reg1 = regs[i].first();
3767 if (reg1->is_stack()) {
3768 // Yuck
3769 reg1 = reg1->bias(out_preserve_stack_slots());
3770 }
3771 VMReg reg2 = regs[i].second();
3772 if (reg2->is_stack()) {
3773 // Yuck
3774 reg2 = reg2->bias(out_preserve_stack_slots());
3775 }
3776 regs[i].set_pair(reg2, reg1);
3777 }
3778 }
3779
3780 // results
3781 *arg_size = cnt;
3782 return regs;
3783 }
3784
3785 // OSR Migration Code
3786 //
3787 // This code is used convert interpreter frames into compiled frames. It is
3788 // called from very start of a compiled OSR nmethod. A temp array is
3789 // allocated to hold the interesting bits of the interpreter frame. All
3790 // active locks are inflated to allow them to move. The displaced headers and
3791 // active interpreter locals are copied into the temp buffer. Then we return
3792 // back to the compiled code. The compiled code then pops the current
3793 // interpreter frame off the stack and pushes a new compiled frame. Then it
3794 // copies the interpreter locals and displaced headers where it wants.
3795 // Finally it calls back to free the temp buffer.
3796 //
3797 // All of this is done NOT at any Safepoint, nor is any safepoint or GC allowed.
3798
3799 JRT_LEAF(intptr_t*, SharedRuntime::OSR_migration_begin( JavaThread *current) )
3800 assert(current == JavaThread::current(), "pre-condition");
3801 JFR_ONLY(Jfr::check_and_process_sample_request(current);)
3802 // During OSR migration, we unwind the interpreted frame and replace it with a compiled
3803 // frame. The stack watermark code below ensures that the interpreted frame is processed
3804 // before it gets unwound. This is helpful as the size of the compiled frame could be
3805 // larger than the interpreted frame, which could result in the new frame not being
3806 // processed correctly.
3807 StackWatermarkSet::before_unwind(current);
3808
3809 //
3810 // This code is dependent on the memory layout of the interpreter local
3811 // array and the monitors. On all of our platforms the layout is identical
3812 // so this code is shared. If some platform lays the their arrays out
3813 // differently then this code could move to platform specific code or
3814 // the code here could be modified to copy items one at a time using
3815 // frame accessor methods and be platform independent.
3816
3817 frame fr = current->last_frame();
3818 assert(fr.is_interpreted_frame(), "");
3819 assert(fr.interpreter_frame_expression_stack_size()==0, "only handle empty stacks");
3820
3821 // Figure out how many monitors are active.
3822 int active_monitor_count = 0;
3823 for (BasicObjectLock *kptr = fr.interpreter_frame_monitor_end();
3824 kptr < fr.interpreter_frame_monitor_begin();
3825 kptr = fr.next_monitor_in_interpreter_frame(kptr) ) {
3826 if (kptr->obj() != nullptr) active_monitor_count++;
3827 }
3828
3829 // QQQ we could place number of active monitors in the array so that compiled code
3830 // could double check it.
3831
3832 Method* moop = fr.interpreter_frame_method();
3833 int max_locals = moop->max_locals();
3834 // Allocate temp buffer, 1 word per local & 2 per active monitor
3835 int buf_size_words = max_locals + active_monitor_count * BasicObjectLock::size();
3836 intptr_t *buf = NEW_C_HEAP_ARRAY(intptr_t,buf_size_words, mtCode);
3837
3838 // Copy the locals. Order is preserved so that loading of longs works.
3839 // Since there's no GC I can copy the oops blindly.
3840 assert(sizeof(HeapWord)==sizeof(intptr_t), "fix this code");
3841 Copy::disjoint_words((HeapWord*)fr.interpreter_frame_local_at(max_locals-1),
3842 (HeapWord*)&buf[0],
3843 max_locals);
3844
3845 // Inflate locks. Copy the displaced headers. Be careful, there can be holes.
3846 int i = max_locals;
3847 for (BasicObjectLock *kptr2 = fr.interpreter_frame_monitor_end();
3848 kptr2 < fr.interpreter_frame_monitor_begin();
3849 kptr2 = fr.next_monitor_in_interpreter_frame(kptr2) ) {
3850 if (kptr2->obj() != nullptr) { // Avoid 'holes' in the monitor array
3851 BasicLock *lock = kptr2->lock();
3852 if (UseObjectMonitorTable) {
3853 buf[i] = (intptr_t)lock->object_monitor_cache();
3854 }
3855 #ifdef ASSERT
3856 else {
3857 buf[i] = badDispHeaderOSR;
3858 }
3859 #endif
3860 i++;
3861 buf[i++] = cast_from_oop<intptr_t>(kptr2->obj());
3862 }
3863 }
3864 assert(i - max_locals == active_monitor_count*2, "found the expected number of monitors");
3865
3866 RegisterMap map(current,
3867 RegisterMap::UpdateMap::skip,
3868 RegisterMap::ProcessFrames::include,
3869 RegisterMap::WalkContinuation::skip);
3870 frame sender = fr.sender(&map);
3871 if (sender.is_interpreted_frame()) {
3872 current->push_cont_fastpath(sender.unextended_sp());
3873 }
3874
3875 return buf;
3876 JRT_END
3877
3878 JRT_LEAF(void, SharedRuntime::OSR_migration_end( intptr_t* buf) )
3879 FREE_C_HEAP_ARRAY(intptr_t, buf);
3880 JRT_END
3881
3882 const char* AdapterHandlerLibrary::name(AdapterHandlerEntry* handler) {
3883 return handler->fingerprint()->as_basic_args_string();
3884 }
3885
3886 uint32_t AdapterHandlerLibrary::id(AdapterHandlerEntry* handler) {
3887 return handler->id();
3888 }
3889
3890 void AdapterHandlerLibrary::print_handler_on(outputStream* st, const CodeBlob* b) {
3891 bool found = false;
3892 #if INCLUDE_CDS
3893 if (AOTCodeCache::is_using_adapter()) {
3894 auto findblob_archived_table = [&] (AdapterHandlerEntry* handler) {
3895 if (b == handler->adapter_blob()) {
3896 found = true;
3897 st->print("Adapter for signature: ");
3898 handler->print_adapter_on(st);
3899 return false; // abort iteration
3900 } else {
3901 return true; // keep looking
3902 }
3903 };
3904 _aot_adapter_handler_table.iterate(findblob_archived_table);
3905 }
3906 #endif // INCLUDE_CDS
3907 if (!found) {
3908 auto findblob_runtime_table = [&] (AdapterFingerPrint* key, AdapterHandlerEntry* handler) {
3909 if (b == handler->adapter_blob()) {
3910 found = true;
3911 st->print("Adapter for signature: ");
3912 handler->print_adapter_on(st);
3913 return false; // abort iteration
3914 } else {
3915 return true; // keep looking
3916 }
3917 };
3918 assert_locked_or_safepoint(AdapterHandlerLibrary_lock);
3919 _adapter_handler_table->iterate(findblob_runtime_table);
3920 }
3921 assert(found, "Should have found handler");
3922 }
3923
3924 void AdapterHandlerEntry::print_adapter_on(outputStream* st) const {
3925 st->print("AHE@" INTPTR_FORMAT ": %s", p2i(this), fingerprint()->as_string());
3926 if (adapter_blob() != nullptr) {
3927 st->print(" i2c: " INTPTR_FORMAT, p2i(get_i2c_entry()));
3928 st->print(" c2i: " INTPTR_FORMAT, p2i(get_c2i_entry()));
3929 st->print(" c2iVE: " INTPTR_FORMAT, p2i(get_c2i_inline_entry()));
3930 st->print(" c2iVROE: " INTPTR_FORMAT, p2i(get_c2i_inline_ro_entry()));
3931 st->print(" c2iUE: " INTPTR_FORMAT, p2i(get_c2i_unverified_entry()));
3932 st->print(" c2iUVE: " INTPTR_FORMAT, p2i(get_c2i_unverified_inline_entry()));
3933 if (get_c2i_no_clinit_check_entry() != nullptr) {
3934 st->print(" c2iNCI: " INTPTR_FORMAT, p2i(get_c2i_no_clinit_check_entry()));
3935 }
3936 }
3937 st->cr();
3938 }
3939
3940 #ifndef PRODUCT
3941
3942 void AdapterHandlerLibrary::print_statistics() {
3943 print_table_statistics();
3944 }
3945
3946 #endif /* PRODUCT */
3947
3948 JRT_LEAF(void, SharedRuntime::enable_stack_reserved_zone(JavaThread* current))
3949 assert(current == JavaThread::current(), "pre-condition");
3950 StackOverflow* overflow_state = current->stack_overflow_state();
3951 overflow_state->enable_stack_reserved_zone(/*check_if_disabled*/true);
3952 overflow_state->set_reserved_stack_activation(current->stack_base());
3953 JRT_END
3954
3955 frame SharedRuntime::look_for_reserved_stack_annotated_method(JavaThread* current, frame fr) {
3956 ResourceMark rm(current);
3957 frame activation;
3958 nmethod* nm = nullptr;
3959 int count = 1;
3960
3961 assert(fr.is_java_frame(), "Must start on Java frame");
3962
3963 RegisterMap map(JavaThread::current(),
3964 RegisterMap::UpdateMap::skip,
3965 RegisterMap::ProcessFrames::skip,
3966 RegisterMap::WalkContinuation::skip); // don't walk continuations
3967 for (; !fr.is_first_frame(); fr = fr.sender(&map)) {
3968 if (!fr.is_java_frame()) {
3969 continue;
3970 }
3971
3972 Method* method = nullptr;
3973 bool found = false;
3974 if (fr.is_interpreted_frame()) {
3975 method = fr.interpreter_frame_method();
3976 if (method != nullptr && method->has_reserved_stack_access()) {
3977 found = true;
3978 }
3979 } else {
3980 CodeBlob* cb = fr.cb();
3981 if (cb != nullptr && cb->is_nmethod()) {
3982 nm = cb->as_nmethod();
3983 method = nm->method();
3984 for (ScopeDesc *sd = nm->scope_desc_near(fr.pc()); sd != nullptr; sd = sd->sender()) {
3985 method = sd->method();
3986 if (method != nullptr && method->has_reserved_stack_access()) {
3987 found = true;
3988 }
3989 }
3990 }
3991 }
3992 if (found) {
3993 activation = fr;
3994 warning("Potentially dangerous stack overflow in "
3995 "ReservedStackAccess annotated method %s [%d]",
3996 method->name_and_sig_as_C_string(), count++);
3997 EventReservedStackActivation event;
3998 if (event.should_commit()) {
3999 event.set_method(method);
4000 event.commit();
4001 }
4002 }
4003 }
4004 return activation;
4005 }
4006
4007 void SharedRuntime::on_slowpath_allocation_exit(JavaThread* current) {
4008 // After any safepoint, just before going back to compiled code,
4009 // we inform the GC that we will be doing initializing writes to
4010 // this object in the future without emitting card-marks, so
4011 // GC may take any compensating steps.
4012
4013 oop new_obj = current->vm_result_oop();
4014 if (new_obj == nullptr) return;
4015
4016 BarrierSet *bs = BarrierSet::barrier_set();
4017 bs->on_slowpath_allocation_exit(current, new_obj);
4018 }
4019
4020 // We are at a compiled code to interpreter call. We need backing
4021 // buffers for all inline type arguments. Allocate an object array to
4022 // hold them (convenient because once we're done with it we don't have
4023 // to worry about freeing it).
4024 oop SharedRuntime::allocate_inline_types_impl(JavaThread* current, methodHandle callee, bool allocate_receiver, TRAPS) {
4025 assert(InlineTypePassFieldsAsArgs, "no reason to call this");
4026 ResourceMark rm;
4027
4028 int nb_slots = 0;
4029 InstanceKlass* holder = callee->method_holder();
4030 allocate_receiver &= !callee->is_static() && holder->is_inline_klass() && callee->is_scalarized_arg(0);
4031 if (allocate_receiver) {
4032 nb_slots++;
4033 }
4034 int arg_num = callee->is_static() ? 0 : 1;
4035 for (SignatureStream ss(callee->signature()); !ss.at_return_type(); ss.next()) {
4036 BasicType bt = ss.type();
4037 if (bt == T_OBJECT && callee->is_scalarized_arg(arg_num)) {
4038 nb_slots++;
4039 }
4040 if (bt != T_VOID) {
4041 arg_num++;
4042 }
4043 }
4044 objArrayOop array_oop = oopFactory::new_objectArray(nb_slots, CHECK_NULL);
4045 objArrayHandle array(THREAD, array_oop);
4046 arg_num = callee->is_static() ? 0 : 1;
4047 int i = 0;
4048 if (allocate_receiver) {
4049 InlineKlass* vk = InlineKlass::cast(holder);
4050 oop res = vk->allocate_instance(CHECK_NULL);
4051 array->obj_at_put(i++, res);
4052 }
4053 for (SignatureStream ss(callee->signature()); !ss.at_return_type(); ss.next()) {
4054 BasicType bt = ss.type();
4055 if (bt == T_OBJECT && callee->is_scalarized_arg(arg_num)) {
4056 InlineKlass* vk = ss.as_inline_klass(holder);
4057 assert(vk != nullptr, "Unexpected klass");
4058 oop res = vk->allocate_instance(CHECK_NULL);
4059 array->obj_at_put(i++, res);
4060 }
4061 if (bt != T_VOID) {
4062 arg_num++;
4063 }
4064 }
4065 return array();
4066 }
4067
4068 JRT_ENTRY(void, SharedRuntime::allocate_inline_types(JavaThread* current, Method* callee_method, bool allocate_receiver))
4069 methodHandle callee(current, callee_method);
4070 oop array = SharedRuntime::allocate_inline_types_impl(current, callee, allocate_receiver, CHECK);
4071 current->set_vm_result_oop(array);
4072 current->set_vm_result_metadata(callee()); // TODO: required to keep callee live?
4073 JRT_END
4074
4075 // We're returning from an interpreted method: load each field into a
4076 // register following the calling convention
4077 JRT_LEAF(void, SharedRuntime::load_inline_type_fields_in_regs(JavaThread* current, oopDesc* res))
4078 {
4079 assert(res->klass()->is_inline_klass(), "only inline types here");
4080 ResourceMark rm;
4081 RegisterMap reg_map(current,
4082 RegisterMap::UpdateMap::include,
4083 RegisterMap::ProcessFrames::include,
4084 RegisterMap::WalkContinuation::skip);
4085 frame stubFrame = current->last_frame();
4086 frame callerFrame = stubFrame.sender(®_map);
4087 assert(callerFrame.is_interpreted_frame(), "should be coming from interpreter");
4088
4089 InlineKlass* vk = InlineKlass::cast(res->klass());
4090
4091 const Array<SigEntry>* sig_vk = vk->extended_sig();
4092 const Array<VMRegPair>* regs = vk->return_regs();
4093
4094 if (regs == nullptr) {
4095 // The fields of the inline klass don't fit in registers, bail out
4096 return;
4097 }
4098
4099 int j = 1;
4100 for (int i = 0; i < sig_vk->length(); i++) {
4101 BasicType bt = sig_vk->at(i)._bt;
4102 if (bt == T_METADATA) {
4103 continue;
4104 }
4105 if (bt == T_VOID) {
4106 if (sig_vk->at(i-1)._bt == T_LONG ||
4107 sig_vk->at(i-1)._bt == T_DOUBLE) {
4108 j++;
4109 }
4110 continue;
4111 }
4112 int off = sig_vk->at(i)._offset;
4113 assert(off > 0, "offset in object should be positive");
4114 VMRegPair pair = regs->at(j);
4115 address loc = reg_map.location(pair.first(), nullptr);
4116 guarantee(loc != nullptr, "bad register save location");
4117 switch(bt) {
4118 case T_BOOLEAN:
4119 *(jboolean*)loc = res->bool_field(off);
4120 break;
4121 case T_CHAR:
4122 *(jchar*)loc = res->char_field(off);
4123 break;
4124 case T_BYTE:
4125 *(jbyte*)loc = res->byte_field(off);
4126 break;
4127 case T_SHORT:
4128 *(jshort*)loc = res->short_field(off);
4129 break;
4130 case T_INT: {
4131 *(jint*)loc = res->int_field(off);
4132 break;
4133 }
4134 case T_LONG:
4135 #ifdef _LP64
4136 *(intptr_t*)loc = res->long_field(off);
4137 #else
4138 Unimplemented();
4139 #endif
4140 break;
4141 case T_OBJECT:
4142 case T_ARRAY: {
4143 *(oop*)loc = res->obj_field(off);
4144 break;
4145 }
4146 case T_FLOAT:
4147 *(jfloat*)loc = res->float_field(off);
4148 break;
4149 case T_DOUBLE:
4150 *(jdouble*)loc = res->double_field(off);
4151 break;
4152 default:
4153 ShouldNotReachHere();
4154 }
4155 j++;
4156 }
4157 assert(j == regs->length(), "missed a field?");
4158
4159 #ifdef ASSERT
4160 VMRegPair pair = regs->at(0);
4161 address loc = reg_map.location(pair.first(), nullptr);
4162 assert(*(oopDesc**)loc == res, "overwritten object");
4163 #endif
4164
4165 current->set_vm_result_oop(res);
4166 }
4167 JRT_END
4168
4169 // We've returned to an interpreted method, the interpreter needs a
4170 // reference to an inline type instance. Allocate it and initialize it
4171 // from field's values in registers.
4172 JRT_BLOCK_ENTRY(void, SharedRuntime::store_inline_type_fields_to_buf(JavaThread* current, intptr_t res))
4173 {
4174 ResourceMark rm;
4175 RegisterMap reg_map(current,
4176 RegisterMap::UpdateMap::include,
4177 RegisterMap::ProcessFrames::include,
4178 RegisterMap::WalkContinuation::skip);
4179 frame stubFrame = current->last_frame();
4180 frame callerFrame = stubFrame.sender(®_map);
4181
4182 #ifdef ASSERT
4183 InlineKlass* verif_vk = InlineKlass::returned_inline_klass(reg_map);
4184 #endif
4185
4186 if (!is_set_nth_bit(res, 0)) {
4187 // We're not returning with inline type fields in registers (the
4188 // calling convention didn't allow it for this inline klass)
4189 assert(!Metaspace::contains((void*)res), "should be oop or pointer in buffer area");
4190 current->set_vm_result_oop((oopDesc*)res);
4191 assert(verif_vk == nullptr, "broken calling convention");
4192 return;
4193 }
4194
4195 clear_nth_bit(res, 0);
4196 InlineKlass* vk = (InlineKlass*)res;
4197 assert(verif_vk == vk, "broken calling convention");
4198 assert(Metaspace::contains((void*)res), "should be klass");
4199
4200 // Allocate handles for every oop field so they are safe in case of
4201 // a safepoint when allocating
4202 GrowableArray<Handle> handles;
4203 vk->save_oop_fields(reg_map, handles);
4204
4205 // It's unsafe to safepoint until we are here
4206 JRT_BLOCK;
4207 {
4208 JavaThread* THREAD = current;
4209 oop vt = vk->realloc_result(reg_map, handles, CHECK);
4210 current->set_vm_result_oop(vt);
4211 }
4212 JRT_BLOCK_END;
4213 }
4214 JRT_END