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