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