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