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