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