1 /*
2 * Copyright (c) 1999, 2022, 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 "asm/codeBuffer.hpp"
27 #include "c1/c1_CodeStubs.hpp"
28 #include "c1/c1_Defs.hpp"
29 #include "c1/c1_FrameMap.hpp"
30 #include "c1/c1_LIRAssembler.hpp"
31 #include "c1/c1_MacroAssembler.hpp"
32 #include "c1/c1_Runtime1.hpp"
33 #include "classfile/javaClasses.inline.hpp"
34 #include "classfile/vmClasses.hpp"
35 #include "classfile/vmSymbols.hpp"
36 #include "code/codeBlob.hpp"
37 #include "code/compiledIC.hpp"
38 #include "code/pcDesc.hpp"
39 #include "code/scopeDesc.hpp"
40 #include "code/vtableStubs.hpp"
41 #include "compiler/compilationPolicy.hpp"
42 #include "compiler/disassembler.hpp"
43 #include "compiler/oopMap.hpp"
44 #include "gc/shared/barrierSet.hpp"
45 #include "gc/shared/c1/barrierSetC1.hpp"
46 #include "gc/shared/collectedHeap.hpp"
47 #include "interpreter/bytecode.hpp"
48 #include "interpreter/interpreter.hpp"
49 #include "jfr/support/jfrIntrinsics.hpp"
50 #include "logging/log.hpp"
51 #include "memory/allocation.inline.hpp"
52 #include "memory/oopFactory.hpp"
53 #include "memory/resourceArea.hpp"
54 #include "memory/universe.hpp"
55 #include "oops/access.inline.hpp"
56 #include "oops/klass.inline.hpp"
57 #include "oops/objArrayOop.inline.hpp"
58 #include "oops/objArrayKlass.hpp"
59 #include "oops/oop.inline.hpp"
60 #include "prims/jvmtiExport.hpp"
61 #include "runtime/atomic.hpp"
62 #include "runtime/fieldDescriptor.inline.hpp"
63 #include "runtime/frame.inline.hpp"
64 #include "runtime/handles.inline.hpp"
65 #include "runtime/interfaceSupport.inline.hpp"
66 #include "runtime/javaCalls.hpp"
67 #include "runtime/sharedRuntime.hpp"
68 #include "runtime/stackWatermarkSet.hpp"
69 #include "runtime/stubRoutines.hpp"
70 #include "runtime/threadCritical.hpp"
71 #include "runtime/vframe.inline.hpp"
72 #include "runtime/vframeArray.hpp"
73 #include "runtime/vm_version.hpp"
74 #include "utilities/copy.hpp"
75 #include "utilities/events.hpp"
76
77
78 // Implementation of StubAssembler
79
80 StubAssembler::StubAssembler(CodeBuffer* code, const char * name, int stub_id) : C1_MacroAssembler(code) {
81 _name = name;
82 _must_gc_arguments = false;
83 _frame_size = no_frame_size;
84 _num_rt_args = 0;
85 _stub_id = stub_id;
86 }
87
88
89 void StubAssembler::set_info(const char* name, bool must_gc_arguments) {
90 _name = name;
91 _must_gc_arguments = must_gc_arguments;
92 }
93
94
95 void StubAssembler::set_frame_size(int size) {
96 if (_frame_size == no_frame_size) {
97 _frame_size = size;
98 }
99 assert(_frame_size == size, "can't change the frame size");
100 }
101
102
103 void StubAssembler::set_num_rt_args(int args) {
104 if (_num_rt_args == 0) {
105 _num_rt_args = args;
106 }
107 assert(_num_rt_args == args, "can't change the number of args");
108 }
109
110 // Implementation of Runtime1
111
112 CodeBlob* Runtime1::_blobs[Runtime1::number_of_ids];
113 const char *Runtime1::_blob_names[] = {
114 RUNTIME1_STUBS(STUB_NAME, LAST_STUB_NAME)
115 };
116
117 #ifndef PRODUCT
118 // statistics
119 int Runtime1::_generic_arraycopystub_cnt = 0;
120 int Runtime1::_arraycopy_slowcase_cnt = 0;
121 int Runtime1::_arraycopy_checkcast_cnt = 0;
122 int Runtime1::_arraycopy_checkcast_attempt_cnt = 0;
123 int Runtime1::_new_type_array_slowcase_cnt = 0;
124 int Runtime1::_new_object_array_slowcase_cnt = 0;
125 int Runtime1::_new_instance_slowcase_cnt = 0;
126 int Runtime1::_new_multi_array_slowcase_cnt = 0;
127 int Runtime1::_monitorenter_slowcase_cnt = 0;
128 int Runtime1::_monitorexit_slowcase_cnt = 0;
129 int Runtime1::_patch_code_slowcase_cnt = 0;
130 int Runtime1::_throw_range_check_exception_count = 0;
131 int Runtime1::_throw_index_exception_count = 0;
132 int Runtime1::_throw_div0_exception_count = 0;
133 int Runtime1::_throw_null_pointer_exception_count = 0;
134 int Runtime1::_throw_class_cast_exception_count = 0;
135 int Runtime1::_throw_incompatible_class_change_error_count = 0;
136 int Runtime1::_throw_count = 0;
137
138 static int _byte_arraycopy_stub_cnt = 0;
139 static int _short_arraycopy_stub_cnt = 0;
140 static int _int_arraycopy_stub_cnt = 0;
141 static int _long_arraycopy_stub_cnt = 0;
142 static int _oop_arraycopy_stub_cnt = 0;
143
144 address Runtime1::arraycopy_count_address(BasicType type) {
145 switch (type) {
146 case T_BOOLEAN:
147 case T_BYTE: return (address)&_byte_arraycopy_stub_cnt;
148 case T_CHAR:
149 case T_SHORT: return (address)&_short_arraycopy_stub_cnt;
150 case T_FLOAT:
151 case T_INT: return (address)&_int_arraycopy_stub_cnt;
152 case T_DOUBLE:
153 case T_LONG: return (address)&_long_arraycopy_stub_cnt;
154 case T_ARRAY:
155 case T_OBJECT: return (address)&_oop_arraycopy_stub_cnt;
156 default:
157 ShouldNotReachHere();
158 return NULL;
159 }
160 }
161
162
163 #endif
164
165 // Simple helper to see if the caller of a runtime stub which
166 // entered the VM has been deoptimized
167
168 static bool caller_is_deopted(JavaThread* current) {
169 RegisterMap reg_map(current,
170 RegisterMap::UpdateMap::skip,
171 RegisterMap::ProcessFrames::include,
172 RegisterMap::WalkContinuation::skip);
173 frame runtime_frame = current->last_frame();
174 frame caller_frame = runtime_frame.sender(®_map);
175 assert(caller_frame.is_compiled_frame(), "must be compiled");
176 return caller_frame.is_deoptimized_frame();
177 }
178
179 // Stress deoptimization
180 static void deopt_caller(JavaThread* current) {
181 if (!caller_is_deopted(current)) {
182 RegisterMap reg_map(current,
183 RegisterMap::UpdateMap::skip,
184 RegisterMap::ProcessFrames::include,
185 RegisterMap::WalkContinuation::skip);
186 frame runtime_frame = current->last_frame();
187 frame caller_frame = runtime_frame.sender(®_map);
188 Deoptimization::deoptimize_frame(current, caller_frame.id());
189 assert(caller_is_deopted(current), "Must be deoptimized");
190 }
191 }
192
193 class StubIDStubAssemblerCodeGenClosure: public StubAssemblerCodeGenClosure {
194 private:
195 Runtime1::StubID _id;
196 public:
197 StubIDStubAssemblerCodeGenClosure(Runtime1::StubID id) : _id(id) {}
198 virtual OopMapSet* generate_code(StubAssembler* sasm) {
199 return Runtime1::generate_code_for(_id, sasm);
200 }
201 };
202
203 CodeBlob* Runtime1::generate_blob(BufferBlob* buffer_blob, int stub_id, const char* name, bool expect_oop_map, StubAssemblerCodeGenClosure* cl) {
204 ResourceMark rm;
205 // create code buffer for code storage
206 CodeBuffer code(buffer_blob);
207
208 OopMapSet* oop_maps;
209 int frame_size;
210 bool must_gc_arguments;
211
212 Compilation::setup_code_buffer(&code, 0);
213
214 // create assembler for code generation
215 StubAssembler* sasm = new StubAssembler(&code, name, stub_id);
216 // generate code for runtime stub
217 oop_maps = cl->generate_code(sasm);
218 assert(oop_maps == NULL || sasm->frame_size() != no_frame_size,
219 "if stub has an oop map it must have a valid frame size");
220 assert(!expect_oop_map || oop_maps != NULL, "must have an oopmap");
221
222 // align so printing shows nop's instead of random code at the end (SimpleStubs are aligned)
223 sasm->align(BytesPerWord);
224 // make sure all code is in code buffer
225 sasm->flush();
226
227 frame_size = sasm->frame_size();
228 must_gc_arguments = sasm->must_gc_arguments();
229 // create blob - distinguish a few special cases
230 CodeBlob* blob = RuntimeStub::new_runtime_stub(name,
231 &code,
232 CodeOffsets::frame_never_safe,
233 frame_size,
234 oop_maps,
235 must_gc_arguments);
236 assert(blob != NULL, "blob must exist");
237 return blob;
238 }
239
240 void Runtime1::generate_blob_for(BufferBlob* buffer_blob, StubID id) {
241 assert(0 <= id && id < number_of_ids, "illegal stub id");
242 bool expect_oop_map = true;
243 #ifdef ASSERT
244 // Make sure that stubs that need oopmaps have them
245 switch (id) {
246 // These stubs don't need to have an oopmap
247 case load_klass_id:
248 case dtrace_object_alloc_id:
249 case slow_subtype_check_id:
250 case fpu2long_stub_id:
251 case unwind_exception_id:
252 case counter_overflow_id:
253 expect_oop_map = false;
254 break;
255 default:
256 break;
257 }
258 #endif
259 StubIDStubAssemblerCodeGenClosure cl(id);
260 CodeBlob* blob = generate_blob(buffer_blob, id, name_for(id), expect_oop_map, &cl);
261 // install blob
262 _blobs[id] = blob;
263 }
264
265 void Runtime1::initialize(BufferBlob* blob) {
266 // platform-dependent initialization
267 initialize_pd();
268 // generate stubs
269 for (int id = 0; id < number_of_ids; id++) generate_blob_for(blob, (StubID)id);
270 // printing
271 #ifndef PRODUCT
272 if (PrintSimpleStubs) {
273 ResourceMark rm;
274 for (int id = 0; id < number_of_ids; id++) {
275 _blobs[id]->print();
276 if (_blobs[id]->oop_maps() != NULL) {
277 _blobs[id]->oop_maps()->print();
278 }
279 }
280 }
281 #endif
282 BarrierSetC1* bs = BarrierSet::barrier_set()->barrier_set_c1();
283 bs->generate_c1_runtime_stubs(blob);
284 }
285
286 CodeBlob* Runtime1::blob_for(StubID id) {
287 assert(0 <= id && id < number_of_ids, "illegal stub id");
288 return _blobs[id];
289 }
290
291
292 const char* Runtime1::name_for(StubID id) {
293 assert(0 <= id && id < number_of_ids, "illegal stub id");
294 return _blob_names[id];
295 }
296
297 const char* Runtime1::name_for_address(address entry) {
298 for (int id = 0; id < number_of_ids; id++) {
299 if (entry == entry_for((StubID)id)) return name_for((StubID)id);
300 }
301
302 #define FUNCTION_CASE(a, f) \
303 if ((intptr_t)a == CAST_FROM_FN_PTR(intptr_t, f)) return #f
304
305 FUNCTION_CASE(entry, os::javaTimeMillis);
306 FUNCTION_CASE(entry, os::javaTimeNanos);
307 FUNCTION_CASE(entry, SharedRuntime::OSR_migration_end);
308 FUNCTION_CASE(entry, SharedRuntime::d2f);
309 FUNCTION_CASE(entry, SharedRuntime::d2i);
310 FUNCTION_CASE(entry, SharedRuntime::d2l);
311 FUNCTION_CASE(entry, SharedRuntime::dcos);
312 FUNCTION_CASE(entry, SharedRuntime::dexp);
313 FUNCTION_CASE(entry, SharedRuntime::dlog);
314 FUNCTION_CASE(entry, SharedRuntime::dlog10);
315 FUNCTION_CASE(entry, SharedRuntime::dpow);
316 FUNCTION_CASE(entry, SharedRuntime::drem);
317 FUNCTION_CASE(entry, SharedRuntime::dsin);
318 FUNCTION_CASE(entry, SharedRuntime::dtan);
319 FUNCTION_CASE(entry, SharedRuntime::f2i);
320 FUNCTION_CASE(entry, SharedRuntime::f2l);
321 FUNCTION_CASE(entry, SharedRuntime::frem);
322 FUNCTION_CASE(entry, SharedRuntime::l2d);
323 FUNCTION_CASE(entry, SharedRuntime::l2f);
324 FUNCTION_CASE(entry, SharedRuntime::ldiv);
325 FUNCTION_CASE(entry, SharedRuntime::lmul);
326 FUNCTION_CASE(entry, SharedRuntime::lrem);
327 FUNCTION_CASE(entry, SharedRuntime::lrem);
328 FUNCTION_CASE(entry, SharedRuntime::dtrace_method_entry);
329 FUNCTION_CASE(entry, SharedRuntime::dtrace_method_exit);
330 FUNCTION_CASE(entry, is_instance_of);
331 FUNCTION_CASE(entry, trace_block_entry);
332 #ifdef JFR_HAVE_INTRINSICS
333 FUNCTION_CASE(entry, JfrTime::time_function());
334 #endif
335 FUNCTION_CASE(entry, StubRoutines::updateBytesCRC32());
336 FUNCTION_CASE(entry, StubRoutines::updateBytesCRC32C());
337 FUNCTION_CASE(entry, StubRoutines::vectorizedMismatch());
338 FUNCTION_CASE(entry, StubRoutines::dexp());
339 FUNCTION_CASE(entry, StubRoutines::dlog());
340 FUNCTION_CASE(entry, StubRoutines::dlog10());
341 FUNCTION_CASE(entry, StubRoutines::dpow());
342 FUNCTION_CASE(entry, StubRoutines::dsin());
343 FUNCTION_CASE(entry, StubRoutines::dcos());
344 FUNCTION_CASE(entry, StubRoutines::dtan());
345 FUNCTION_CASE(entry, StubRoutines::cont_doYield());
346
347 #undef FUNCTION_CASE
348
349 // Soft float adds more runtime names.
350 return pd_name_for_address(entry);
351 }
352
353
354 JRT_ENTRY(void, Runtime1::new_instance(JavaThread* current, Klass* klass))
355 #ifndef PRODUCT
356 if (PrintC1Statistics) {
357 _new_instance_slowcase_cnt++;
358 }
359 #endif
360 assert(klass->is_klass(), "not a class");
361 Handle holder(current, klass->klass_holder()); // keep the klass alive
362 InstanceKlass* h = InstanceKlass::cast(klass);
363 h->check_valid_for_instantiation(true, CHECK);
364 // make sure klass is initialized
365 h->initialize(CHECK);
366 // allocate instance and return via TLS
367 oop obj = h->allocate_instance(CHECK);
368 current->set_vm_result(obj);
369 JRT_END
370
371
372 JRT_ENTRY(void, Runtime1::new_type_array(JavaThread* current, Klass* klass, jint length))
373 #ifndef PRODUCT
374 if (PrintC1Statistics) {
375 _new_type_array_slowcase_cnt++;
376 }
377 #endif
378 // Note: no handle for klass needed since they are not used
379 // anymore after new_typeArray() and no GC can happen before.
380 // (This may have to change if this code changes!)
381 assert(klass->is_klass(), "not a class");
382 BasicType elt_type = TypeArrayKlass::cast(klass)->element_type();
383 oop obj = oopFactory::new_typeArray(elt_type, length, CHECK);
384 current->set_vm_result(obj);
385 // This is pretty rare but this runtime patch is stressful to deoptimization
386 // if we deoptimize here so force a deopt to stress the path.
387 if (DeoptimizeALot) {
388 deopt_caller(current);
389 }
390
391 JRT_END
392
393
394 JRT_ENTRY(void, Runtime1::new_object_array(JavaThread* current, Klass* array_klass, jint length))
395 #ifndef PRODUCT
396 if (PrintC1Statistics) {
397 _new_object_array_slowcase_cnt++;
398 }
399 #endif
400 // Note: no handle for klass needed since they are not used
401 // anymore after new_objArray() and no GC can happen before.
402 // (This may have to change if this code changes!)
403 assert(array_klass->is_klass(), "not a class");
404 Handle holder(current, array_klass->klass_holder()); // keep the klass alive
405 Klass* elem_klass = ObjArrayKlass::cast(array_klass)->element_klass();
406 objArrayOop obj = oopFactory::new_objArray(elem_klass, length, CHECK);
407 current->set_vm_result(obj);
408 // This is pretty rare but this runtime patch is stressful to deoptimization
409 // if we deoptimize here so force a deopt to stress the path.
410 if (DeoptimizeALot) {
411 deopt_caller(current);
412 }
413 JRT_END
414
415
416 JRT_ENTRY(void, Runtime1::new_multi_array(JavaThread* current, Klass* klass, int rank, jint* dims))
417 #ifndef PRODUCT
418 if (PrintC1Statistics) {
419 _new_multi_array_slowcase_cnt++;
420 }
421 #endif
422 assert(klass->is_klass(), "not a class");
423 assert(rank >= 1, "rank must be nonzero");
424 Handle holder(current, klass->klass_holder()); // keep the klass alive
425 oop obj = ArrayKlass::cast(klass)->multi_allocate(rank, dims, CHECK);
426 current->set_vm_result(obj);
427 JRT_END
428
429
430 JRT_ENTRY(void, Runtime1::unimplemented_entry(JavaThread* current, StubID id))
431 tty->print_cr("Runtime1::entry_for(%d) returned unimplemented entry point", id);
432 JRT_END
433
434
435 JRT_ENTRY(void, Runtime1::throw_array_store_exception(JavaThread* current, oopDesc* obj))
436 ResourceMark rm(current);
437 const char* klass_name = obj->klass()->external_name();
438 SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ArrayStoreException(), klass_name);
439 JRT_END
440
441
442 // counter_overflow() is called from within C1-compiled methods. The enclosing method is the method
443 // associated with the top activation record. The inlinee (that is possibly included in the enclosing
444 // method) method is passed as an argument. In order to do that it is embedded in the code as
445 // a constant.
446 static nmethod* counter_overflow_helper(JavaThread* current, int branch_bci, Method* m) {
447 nmethod* osr_nm = NULL;
448 methodHandle method(current, m);
449
450 RegisterMap map(current,
451 RegisterMap::UpdateMap::skip,
452 RegisterMap::ProcessFrames::include,
453 RegisterMap::WalkContinuation::skip);
454 frame fr = current->last_frame().sender(&map);
455 nmethod* nm = (nmethod*) fr.cb();
456 assert(nm!= NULL && nm->is_nmethod(), "Sanity check");
457 methodHandle enclosing_method(current, nm->method());
458
459 CompLevel level = (CompLevel)nm->comp_level();
460 int bci = InvocationEntryBci;
461 if (branch_bci != InvocationEntryBci) {
462 // Compute destination bci
463 address pc = method()->code_base() + branch_bci;
464 Bytecodes::Code branch = Bytecodes::code_at(method(), pc);
465 int offset = 0;
466 switch (branch) {
467 case Bytecodes::_if_icmplt: case Bytecodes::_iflt:
468 case Bytecodes::_if_icmpgt: case Bytecodes::_ifgt:
469 case Bytecodes::_if_icmple: case Bytecodes::_ifle:
470 case Bytecodes::_if_icmpge: case Bytecodes::_ifge:
471 case Bytecodes::_if_icmpeq: case Bytecodes::_if_acmpeq: case Bytecodes::_ifeq:
472 case Bytecodes::_if_icmpne: case Bytecodes::_if_acmpne: case Bytecodes::_ifne:
473 case Bytecodes::_ifnull: case Bytecodes::_ifnonnull: case Bytecodes::_goto:
474 offset = (int16_t)Bytes::get_Java_u2(pc + 1);
475 break;
476 case Bytecodes::_goto_w:
477 offset = Bytes::get_Java_u4(pc + 1);
478 break;
479 default: ;
480 }
481 bci = branch_bci + offset;
482 }
483 osr_nm = CompilationPolicy::event(enclosing_method, method, branch_bci, bci, level, nm, current);
484 return osr_nm;
485 }
486
487 JRT_BLOCK_ENTRY(address, Runtime1::counter_overflow(JavaThread* current, int bci, Method* method))
488 nmethod* osr_nm;
489 JRT_BLOCK
490 osr_nm = counter_overflow_helper(current, bci, method);
491 if (osr_nm != NULL) {
492 RegisterMap map(current,
493 RegisterMap::UpdateMap::skip,
494 RegisterMap::ProcessFrames::include,
495 RegisterMap::WalkContinuation::skip);
496 frame fr = current->last_frame().sender(&map);
497 Deoptimization::deoptimize_frame(current, fr.id());
498 }
499 JRT_BLOCK_END
500 return NULL;
501 JRT_END
502
503 extern void vm_exit(int code);
504
505 // Enter this method from compiled code handler below. This is where we transition
506 // to VM mode. This is done as a helper routine so that the method called directly
507 // from compiled code does not have to transition to VM. This allows the entry
508 // method to see if the nmethod that we have just looked up a handler for has
509 // been deoptimized while we were in the vm. This simplifies the assembly code
510 // cpu directories.
511 //
512 // We are entering here from exception stub (via the entry method below)
513 // If there is a compiled exception handler in this method, we will continue there;
514 // otherwise we will unwind the stack and continue at the caller of top frame method
515 // Note: we enter in Java using a special JRT wrapper. This wrapper allows us to
516 // control the area where we can allow a safepoint. After we exit the safepoint area we can
517 // check to see if the handler we are going to return is now in a nmethod that has
518 // been deoptimized. If that is the case we return the deopt blob
519 // unpack_with_exception entry instead. This makes life for the exception blob easier
520 // because making that same check and diverting is painful from assembly language.
521 JRT_ENTRY_NO_ASYNC(static address, exception_handler_for_pc_helper(JavaThread* current, oopDesc* ex, address pc, nmethod*& nm))
522 // Reset method handle flag.
523 current->set_is_method_handle_return(false);
524
525 Handle exception(current, ex);
526
527 // This function is called when we are about to throw an exception. Therefore,
528 // we have to poll the stack watermark barrier to make sure that not yet safe
529 // stack frames are made safe before returning into them.
530 if (current->last_frame().cb() == Runtime1::blob_for(Runtime1::handle_exception_from_callee_id)) {
531 // The Runtime1::handle_exception_from_callee_id handler is invoked after the
532 // frame has been unwound. It instead builds its own stub frame, to call the
533 // runtime. But the throwing frame has already been unwound here.
534 StackWatermarkSet::after_unwind(current);
535 }
536
537 nm = CodeCache::find_nmethod(pc);
538 assert(nm != NULL, "this is not an nmethod");
539 // Adjust the pc as needed/
540 if (nm->is_deopt_pc(pc)) {
541 RegisterMap map(current,
542 RegisterMap::UpdateMap::skip,
543 RegisterMap::ProcessFrames::include,
544 RegisterMap::WalkContinuation::skip);
545 frame exception_frame = current->last_frame().sender(&map);
546 // if the frame isn't deopted then pc must not correspond to the caller of last_frame
547 assert(exception_frame.is_deoptimized_frame(), "must be deopted");
548 pc = exception_frame.pc();
549 }
550 assert(exception.not_null(), "NULL exceptions should be handled by throw_exception");
551 // Check that exception is a subclass of Throwable
552 assert(exception->is_a(vmClasses::Throwable_klass()),
553 "Exception not subclass of Throwable");
554
555 // debugging support
556 // tracing
557 if (log_is_enabled(Info, exceptions)) {
558 ResourceMark rm;
559 stringStream tempst;
560 assert(nm->method() != NULL, "Unexpected NULL method()");
561 tempst.print("C1 compiled method <%s>\n"
562 " at PC" INTPTR_FORMAT " for thread " INTPTR_FORMAT,
563 nm->method()->print_value_string(), p2i(pc), p2i(current));
564 Exceptions::log_exception(exception, tempst.as_string());
565 }
566 // for AbortVMOnException flag
567 Exceptions::debug_check_abort(exception);
568
569 // Check the stack guard pages and re-enable them if necessary and there is
570 // enough space on the stack to do so. Use fast exceptions only if the guard
571 // pages are enabled.
572 bool guard_pages_enabled = current->stack_overflow_state()->reguard_stack_if_needed();
573
574 if (JvmtiExport::can_post_on_exceptions()) {
575 // To ensure correct notification of exception catches and throws
576 // we have to deoptimize here. If we attempted to notify the
577 // catches and throws during this exception lookup it's possible
578 // we could deoptimize on the way out of the VM and end back in
579 // the interpreter at the throw site. This would result in double
580 // notifications since the interpreter would also notify about
581 // these same catches and throws as it unwound the frame.
582
583 RegisterMap reg_map(current,
584 RegisterMap::UpdateMap::include,
585 RegisterMap::ProcessFrames::include,
586 RegisterMap::WalkContinuation::skip);
587 frame stub_frame = current->last_frame();
588 frame caller_frame = stub_frame.sender(®_map);
589
590 // We don't really want to deoptimize the nmethod itself since we
591 // can actually continue in the exception handler ourselves but I
592 // don't see an easy way to have the desired effect.
593 Deoptimization::deoptimize_frame(current, caller_frame.id());
594 assert(caller_is_deopted(current), "Must be deoptimized");
595
596 return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
597 }
598
599 // ExceptionCache is used only for exceptions at call sites and not for implicit exceptions
600 if (guard_pages_enabled) {
601 address fast_continuation = nm->handler_for_exception_and_pc(exception, pc);
602 if (fast_continuation != NULL) {
603 // Set flag if return address is a method handle call site.
604 current->set_is_method_handle_return(nm->is_method_handle_return(pc));
605 return fast_continuation;
606 }
607 }
608
609 // If the stack guard pages are enabled, check whether there is a handler in
610 // the current method. Otherwise (guard pages disabled), force an unwind and
611 // skip the exception cache update (i.e., just leave continuation==NULL).
612 address continuation = NULL;
613 if (guard_pages_enabled) {
614
615 // New exception handling mechanism can support inlined methods
616 // with exception handlers since the mappings are from PC to PC
617
618 // Clear out the exception oop and pc since looking up an
619 // exception handler can cause class loading, which might throw an
620 // exception and those fields are expected to be clear during
621 // normal bytecode execution.
622 current->clear_exception_oop_and_pc();
623
624 bool recursive_exception = false;
625 continuation = SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, false, false, recursive_exception);
626 // If an exception was thrown during exception dispatch, the exception oop may have changed
627 current->set_exception_oop(exception());
628 current->set_exception_pc(pc);
629
630 // the exception cache is used only by non-implicit exceptions
631 // Update the exception cache only when there didn't happen
632 // another exception during the computation of the compiled
633 // exception handler. Checking for exception oop equality is not
634 // sufficient because some exceptions are pre-allocated and reused.
635 if (continuation != NULL && !recursive_exception) {
636 nm->add_handler_for_exception_and_pc(exception, pc, continuation);
637 }
638 }
639
640 current->set_vm_result(exception());
641 // Set flag if return address is a method handle call site.
642 current->set_is_method_handle_return(nm->is_method_handle_return(pc));
643
644 if (log_is_enabled(Info, exceptions)) {
645 ResourceMark rm;
646 log_info(exceptions)("Thread " PTR_FORMAT " continuing at PC " PTR_FORMAT
647 " for exception thrown at PC " PTR_FORMAT,
648 p2i(current), p2i(continuation), p2i(pc));
649 }
650
651 return continuation;
652 JRT_END
653
654 // Enter this method from compiled code only if there is a Java exception handler
655 // in the method handling the exception.
656 // We are entering here from exception stub. We don't do a normal VM transition here.
657 // We do it in a helper. This is so we can check to see if the nmethod we have just
658 // searched for an exception handler has been deoptimized in the meantime.
659 address Runtime1::exception_handler_for_pc(JavaThread* current) {
660 oop exception = current->exception_oop();
661 address pc = current->exception_pc();
662 // Still in Java mode
663 DEBUG_ONLY(NoHandleMark nhm);
664 nmethod* nm = NULL;
665 address continuation = NULL;
666 {
667 // Enter VM mode by calling the helper
668 ResetNoHandleMark rnhm;
669 continuation = exception_handler_for_pc_helper(current, exception, pc, nm);
670 }
671 // Back in JAVA, use no oops DON'T safepoint
672
673 // Now check to see if the nmethod we were called from is now deoptimized.
674 // If so we must return to the deopt blob and deoptimize the nmethod
675 if (nm != NULL && caller_is_deopted(current)) {
676 continuation = SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
677 }
678
679 assert(continuation != NULL, "no handler found");
680 return continuation;
681 }
682
683
684 JRT_ENTRY(void, Runtime1::throw_range_check_exception(JavaThread* current, int index, arrayOopDesc* a))
685 #ifndef PRODUCT
686 if (PrintC1Statistics) {
687 _throw_range_check_exception_count++;
688 }
689 #endif
690 const int len = 35;
691 assert(len < strlen("Index %d out of bounds for length %d"), "Must allocate more space for message.");
692 char message[2 * jintAsStringSize + len];
693 sprintf(message, "Index %d out of bounds for length %d", index, a->length());
694 SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), message);
695 JRT_END
696
697
698 JRT_ENTRY(void, Runtime1::throw_index_exception(JavaThread* current, int index))
699 #ifndef PRODUCT
700 if (PrintC1Statistics) {
701 _throw_index_exception_count++;
702 }
703 #endif
704 char message[16];
705 sprintf(message, "%d", index);
706 SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_IndexOutOfBoundsException(), message);
707 JRT_END
708
709
710 JRT_ENTRY(void, Runtime1::throw_div0_exception(JavaThread* current))
711 #ifndef PRODUCT
712 if (PrintC1Statistics) {
713 _throw_div0_exception_count++;
714 }
715 #endif
716 SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ArithmeticException(), "/ by zero");
717 JRT_END
718
719
720 JRT_ENTRY(void, Runtime1::throw_null_pointer_exception(JavaThread* current))
721 #ifndef PRODUCT
722 if (PrintC1Statistics) {
723 _throw_null_pointer_exception_count++;
724 }
725 #endif
726 SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_NullPointerException());
727 JRT_END
728
729
730 JRT_ENTRY(void, Runtime1::throw_class_cast_exception(JavaThread* current, oopDesc* object))
731 #ifndef PRODUCT
732 if (PrintC1Statistics) {
733 _throw_class_cast_exception_count++;
734 }
735 #endif
736 ResourceMark rm(current);
737 char* message = SharedRuntime::generate_class_cast_message(current, object->klass());
738 SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ClassCastException(), message);
739 JRT_END
740
741
742 JRT_ENTRY(void, Runtime1::throw_incompatible_class_change_error(JavaThread* current))
743 #ifndef PRODUCT
744 if (PrintC1Statistics) {
745 _throw_incompatible_class_change_error_count++;
746 }
747 #endif
748 ResourceMark rm(current);
749 SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_IncompatibleClassChangeError());
750 JRT_END
751
752
753 JRT_BLOCK_ENTRY(void, Runtime1::monitorenter(JavaThread* current, oopDesc* obj, BasicObjectLock* lock))
754 #ifndef PRODUCT
755 if (PrintC1Statistics) {
756 _monitorenter_slowcase_cnt++;
757 }
758 #endif
759 if (UseHeavyMonitors) {
760 lock->set_obj(obj);
761 }
762 assert(obj == lock->obj(), "must match");
763 SharedRuntime::monitor_enter_helper(obj, lock->lock(), current);
764 JRT_END
765
766
767 JRT_LEAF(void, Runtime1::monitorexit(JavaThread* current, BasicObjectLock* lock))
768 #ifndef PRODUCT
769 if (PrintC1Statistics) {
770 _monitorexit_slowcase_cnt++;
771 }
772 #endif
773 assert(current->last_Java_sp(), "last_Java_sp must be set");
774 oop obj = lock->obj();
775 assert(oopDesc::is_oop(obj), "must be NULL or an object");
776 SharedRuntime::monitor_exit_helper(obj, lock->lock(), current);
777 JRT_END
778
779 // Cf. OptoRuntime::deoptimize_caller_frame
780 JRT_ENTRY(void, Runtime1::deoptimize(JavaThread* current, jint trap_request))
781 // Called from within the owner thread, so no need for safepoint
782 RegisterMap reg_map(current,
783 RegisterMap::UpdateMap::skip,
784 RegisterMap::ProcessFrames::include,
785 RegisterMap::WalkContinuation::skip);
786 frame stub_frame = current->last_frame();
787 assert(stub_frame.is_runtime_frame(), "Sanity check");
788 frame caller_frame = stub_frame.sender(®_map);
789 nmethod* nm = caller_frame.cb()->as_nmethod_or_null();
790 assert(nm != NULL, "Sanity check");
791 methodHandle method(current, nm->method());
792 assert(nm == CodeCache::find_nmethod(caller_frame.pc()), "Should be the same");
793 Deoptimization::DeoptAction action = Deoptimization::trap_request_action(trap_request);
794 Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(trap_request);
795
796 if (action == Deoptimization::Action_make_not_entrant) {
797 if (nm->make_not_entrant()) {
798 if (reason == Deoptimization::Reason_tenured) {
799 MethodData* trap_mdo = Deoptimization::get_method_data(current, method, true /*create_if_missing*/);
800 if (trap_mdo != NULL) {
801 trap_mdo->inc_tenure_traps();
802 }
803 }
804 }
805 }
806
807 // Deoptimize the caller frame.
808 Deoptimization::deoptimize_frame(current, caller_frame.id());
809 // Return to the now deoptimized frame.
810 JRT_END
811
812
813 #ifndef DEOPTIMIZE_WHEN_PATCHING
814
815 static Klass* resolve_field_return_klass(const methodHandle& caller, int bci, TRAPS) {
816 Bytecode_field field_access(caller, bci);
817 // This can be static or non-static field access
818 Bytecodes::Code code = field_access.code();
819
820 // We must load class, initialize class and resolve the field
821 fieldDescriptor result; // initialize class if needed
822 constantPoolHandle constants(THREAD, caller->constants());
823 LinkResolver::resolve_field_access(result, constants, field_access.index(), caller, Bytecodes::java_code(code), CHECK_NULL);
824 return result.field_holder();
825 }
826
827
828 //
829 // This routine patches sites where a class wasn't loaded or
830 // initialized at the time the code was generated. It handles
831 // references to classes, fields and forcing of initialization. Most
832 // of the cases are straightforward and involving simply forcing
833 // resolution of a class, rewriting the instruction stream with the
834 // needed constant and replacing the call in this function with the
835 // patched code. The case for static field is more complicated since
836 // the thread which is in the process of initializing a class can
837 // access it's static fields but other threads can't so the code
838 // either has to deoptimize when this case is detected or execute a
839 // check that the current thread is the initializing thread. The
840 // current
841 //
842 // Patches basically look like this:
843 //
844 //
845 // patch_site: jmp patch stub ;; will be patched
846 // continue: ...
847 // ...
848 // ...
849 // ...
850 //
851 // They have a stub which looks like this:
852 //
853 // ;; patch body
854 // movl <const>, reg (for class constants)
855 // <or> movl [reg1 + <const>], reg (for field offsets)
856 // <or> movl reg, [reg1 + <const>] (for field offsets)
857 // <being_init offset> <bytes to copy> <bytes to skip>
858 // patch_stub: call Runtime1::patch_code (through a runtime stub)
859 // jmp patch_site
860 //
861 //
862 // A normal patch is done by rewriting the patch body, usually a move,
863 // and then copying it into place over top of the jmp instruction
864 // being careful to flush caches and doing it in an MP-safe way. The
865 // constants following the patch body are used to find various pieces
866 // of the patch relative to the call site for Runtime1::patch_code.
867 // The case for getstatic and putstatic is more complicated because
868 // getstatic and putstatic have special semantics when executing while
869 // the class is being initialized. getstatic/putstatic on a class
870 // which is being_initialized may be executed by the initializing
871 // thread but other threads have to block when they execute it. This
872 // is accomplished in compiled code by executing a test of the current
873 // thread against the initializing thread of the class. It's emitted
874 // as boilerplate in their stub which allows the patched code to be
875 // executed before it's copied back into the main body of the nmethod.
876 //
877 // being_init: get_thread(<tmp reg>
878 // cmpl [reg1 + <init_thread_offset>], <tmp reg>
879 // jne patch_stub
880 // movl [reg1 + <const>], reg (for field offsets) <or>
881 // movl reg, [reg1 + <const>] (for field offsets)
882 // jmp continue
883 // <being_init offset> <bytes to copy> <bytes to skip>
884 // patch_stub: jmp Runtim1::patch_code (through a runtime stub)
885 // jmp patch_site
886 //
887 // If the class is being initialized the patch body is rewritten and
888 // the patch site is rewritten to jump to being_init, instead of
889 // patch_stub. Whenever this code is executed it checks the current
890 // thread against the initializing thread so other threads will enter
891 // the runtime and end up blocked waiting the class to finish
892 // initializing inside the calls to resolve_field below. The
893 // initializing class will continue on it's way. Once the class is
894 // fully_initialized, the intializing_thread of the class becomes
895 // NULL, so the next thread to execute this code will fail the test,
896 // call into patch_code and complete the patching process by copying
897 // the patch body back into the main part of the nmethod and resume
898 // executing.
899
900 // NB:
901 //
902 // Patchable instruction sequences inherently exhibit race conditions,
903 // where thread A is patching an instruction at the same time thread B
904 // is executing it. The algorithms we use ensure that any observation
905 // that B can make on any intermediate states during A's patching will
906 // always end up with a correct outcome. This is easiest if there are
907 // few or no intermediate states. (Some inline caches have two
908 // related instructions that must be patched in tandem. For those,
909 // intermediate states seem to be unavoidable, but we will get the
910 // right answer from all possible observation orders.)
911 //
912 // When patching the entry instruction at the head of a method, or a
913 // linkable call instruction inside of a method, we try very hard to
914 // use a patch sequence which executes as a single memory transaction.
915 // This means, in practice, that when thread A patches an instruction,
916 // it should patch a 32-bit or 64-bit word that somehow overlaps the
917 // instruction or is contained in it. We believe that memory hardware
918 // will never break up such a word write, if it is naturally aligned
919 // for the word being written. We also know that some CPUs work very
920 // hard to create atomic updates even of naturally unaligned words,
921 // but we don't want to bet the farm on this always working.
922 //
923 // Therefore, if there is any chance of a race condition, we try to
924 // patch only naturally aligned words, as single, full-word writes.
925
926 JRT_ENTRY(void, Runtime1::patch_code(JavaThread* current, Runtime1::StubID stub_id ))
927 #ifndef PRODUCT
928 if (PrintC1Statistics) {
929 _patch_code_slowcase_cnt++;
930 }
931 #endif
932
933 ResourceMark rm(current);
934 RegisterMap reg_map(current,
935 RegisterMap::UpdateMap::skip,
936 RegisterMap::ProcessFrames::include,
937 RegisterMap::WalkContinuation::skip);
938 frame runtime_frame = current->last_frame();
939 frame caller_frame = runtime_frame.sender(®_map);
940
941 // last java frame on stack
942 vframeStream vfst(current, true);
943 assert(!vfst.at_end(), "Java frame must exist");
944
945 methodHandle caller_method(current, vfst.method());
946 // Note that caller_method->code() may not be same as caller_code because of OSR's
947 // Note also that in the presence of inlining it is not guaranteed
948 // that caller_method() == caller_code->method()
949
950 int bci = vfst.bci();
951 Bytecodes::Code code = caller_method()->java_code_at(bci);
952
953 // this is used by assertions in the access_field_patching_id
954 BasicType patch_field_type = T_ILLEGAL;
955 bool deoptimize_for_volatile = false;
956 bool deoptimize_for_atomic = false;
957 int patch_field_offset = -1;
958 Klass* init_klass = NULL; // klass needed by load_klass_patching code
959 Klass* load_klass = NULL; // klass needed by load_klass_patching code
960 Handle mirror(current, NULL); // oop needed by load_mirror_patching code
961 Handle appendix(current, NULL); // oop needed by appendix_patching code
962 bool load_klass_or_mirror_patch_id =
963 (stub_id == Runtime1::load_klass_patching_id || stub_id == Runtime1::load_mirror_patching_id);
964
965 if (stub_id == Runtime1::access_field_patching_id) {
966
967 Bytecode_field field_access(caller_method, bci);
968 fieldDescriptor result; // initialize class if needed
969 Bytecodes::Code code = field_access.code();
970 constantPoolHandle constants(current, caller_method->constants());
971 LinkResolver::resolve_field_access(result, constants, field_access.index(), caller_method, Bytecodes::java_code(code), CHECK);
972 patch_field_offset = result.offset();
973
974 // If we're patching a field which is volatile then at compile it
975 // must not have been know to be volatile, so the generated code
976 // isn't correct for a volatile reference. The nmethod has to be
977 // deoptimized so that the code can be regenerated correctly.
978 // This check is only needed for access_field_patching since this
979 // is the path for patching field offsets. load_klass is only
980 // used for patching references to oops which don't need special
981 // handling in the volatile case.
982
983 deoptimize_for_volatile = result.access_flags().is_volatile();
984
985 // If we are patching a field which should be atomic, then
986 // the generated code is not correct either, force deoptimizing.
987 // We need to only cover T_LONG and T_DOUBLE fields, as we can
988 // break access atomicity only for them.
989
990 // Strictly speaking, the deoptimization on 64-bit platforms
991 // is unnecessary, and T_LONG stores on 32-bit platforms need
992 // to be handled by special patching code when AlwaysAtomicAccesses
993 // becomes product feature. At this point, we are still going
994 // for the deoptimization for consistency against volatile
995 // accesses.
996
997 patch_field_type = result.field_type();
998 deoptimize_for_atomic = (AlwaysAtomicAccesses && (patch_field_type == T_DOUBLE || patch_field_type == T_LONG));
999
1000 } else if (load_klass_or_mirror_patch_id) {
1001 Klass* k = NULL;
1002 switch (code) {
1003 case Bytecodes::_putstatic:
1004 case Bytecodes::_getstatic:
1005 { Klass* klass = resolve_field_return_klass(caller_method, bci, CHECK);
1006 init_klass = klass;
1007 mirror = Handle(current, klass->java_mirror());
1008 }
1009 break;
1010 case Bytecodes::_new:
1011 { Bytecode_new bnew(caller_method(), caller_method->bcp_from(bci));
1012 k = caller_method->constants()->klass_at(bnew.index(), CHECK);
1013 }
1014 break;
1015 case Bytecodes::_multianewarray:
1016 { Bytecode_multianewarray mna(caller_method(), caller_method->bcp_from(bci));
1017 k = caller_method->constants()->klass_at(mna.index(), CHECK);
1018 }
1019 break;
1020 case Bytecodes::_instanceof:
1021 { Bytecode_instanceof io(caller_method(), caller_method->bcp_from(bci));
1022 k = caller_method->constants()->klass_at(io.index(), CHECK);
1023 }
1024 break;
1025 case Bytecodes::_checkcast:
1026 { Bytecode_checkcast cc(caller_method(), caller_method->bcp_from(bci));
1027 k = caller_method->constants()->klass_at(cc.index(), CHECK);
1028 }
1029 break;
1030 case Bytecodes::_anewarray:
1031 { Bytecode_anewarray anew(caller_method(), caller_method->bcp_from(bci));
1032 Klass* ek = caller_method->constants()->klass_at(anew.index(), CHECK);
1033 k = ek->array_klass(CHECK);
1034 }
1035 break;
1036 case Bytecodes::_ldc:
1037 case Bytecodes::_ldc_w:
1038 case Bytecodes::_ldc2_w:
1039 {
1040 Bytecode_loadconstant cc(caller_method, bci);
1041 oop m = cc.resolve_constant(CHECK);
1042 mirror = Handle(current, m);
1043 }
1044 break;
1045 default: fatal("unexpected bytecode for load_klass_or_mirror_patch_id");
1046 }
1047 load_klass = k;
1048 } else if (stub_id == load_appendix_patching_id) {
1049 Bytecode_invoke bytecode(caller_method, bci);
1050 Bytecodes::Code bc = bytecode.invoke_code();
1051
1052 CallInfo info;
1053 constantPoolHandle pool(current, caller_method->constants());
1054 int index = bytecode.index();
1055 LinkResolver::resolve_invoke(info, Handle(), pool, index, bc, CHECK);
1056 switch (bc) {
1057 case Bytecodes::_invokehandle: {
1058 int cache_index = ConstantPool::decode_cpcache_index(index, true);
1059 assert(cache_index >= 0 && cache_index < pool->cache()->length(), "unexpected cache index");
1060 ConstantPoolCacheEntry* cpce = pool->cache()->entry_at(cache_index);
1061 cpce->set_method_handle(pool, info);
1062 appendix = Handle(current, cpce->appendix_if_resolved(pool)); // just in case somebody already resolved the entry
1063 break;
1064 }
1065 case Bytecodes::_invokedynamic: {
1066 ConstantPoolCacheEntry* cpce = pool->invokedynamic_cp_cache_entry_at(index);
1067 cpce->set_dynamic_call(pool, info);
1068 appendix = Handle(current, cpce->appendix_if_resolved(pool)); // just in case somebody already resolved the entry
1069 break;
1070 }
1071 default: fatal("unexpected bytecode for load_appendix_patching_id");
1072 }
1073 } else {
1074 ShouldNotReachHere();
1075 }
1076
1077 if (deoptimize_for_volatile || deoptimize_for_atomic) {
1078 // At compile time we assumed the field wasn't volatile/atomic but after
1079 // loading it turns out it was volatile/atomic so we have to throw the
1080 // compiled code out and let it be regenerated.
1081 if (TracePatching) {
1082 if (deoptimize_for_volatile) {
1083 tty->print_cr("Deoptimizing for patching volatile field reference");
1084 }
1085 if (deoptimize_for_atomic) {
1086 tty->print_cr("Deoptimizing for patching atomic field reference");
1087 }
1088 }
1089
1090 // It's possible the nmethod was invalidated in the last
1091 // safepoint, but if it's still alive then make it not_entrant.
1092 nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
1093 if (nm != NULL) {
1094 nm->make_not_entrant();
1095 }
1096
1097 Deoptimization::deoptimize_frame(current, caller_frame.id());
1098
1099 // Return to the now deoptimized frame.
1100 }
1101
1102 // Now copy code back
1103
1104 {
1105 MutexLocker ml_patch (current, Patching_lock, Mutex::_no_safepoint_check_flag);
1106 //
1107 // Deoptimization may have happened while we waited for the lock.
1108 // In that case we don't bother to do any patching we just return
1109 // and let the deopt happen
1110 if (!caller_is_deopted(current)) {
1111 NativeGeneralJump* jump = nativeGeneralJump_at(caller_frame.pc());
1112 address instr_pc = jump->jump_destination();
1113 NativeInstruction* ni = nativeInstruction_at(instr_pc);
1114 if (ni->is_jump() ) {
1115 // the jump has not been patched yet
1116 // The jump destination is slow case and therefore not part of the stubs
1117 // (stubs are only for StaticCalls)
1118
1119 // format of buffer
1120 // ....
1121 // instr byte 0 <-- copy_buff
1122 // instr byte 1
1123 // ..
1124 // instr byte n-1
1125 // n
1126 // .... <-- call destination
1127
1128 address stub_location = caller_frame.pc() + PatchingStub::patch_info_offset();
1129 unsigned char* byte_count = (unsigned char*) (stub_location - 1);
1130 unsigned char* byte_skip = (unsigned char*) (stub_location - 2);
1131 unsigned char* being_initialized_entry_offset = (unsigned char*) (stub_location - 3);
1132 address copy_buff = stub_location - *byte_skip - *byte_count;
1133 address being_initialized_entry = stub_location - *being_initialized_entry_offset;
1134 if (TracePatching) {
1135 ttyLocker ttyl;
1136 tty->print_cr(" Patching %s at bci %d at address " INTPTR_FORMAT " (%s)", Bytecodes::name(code), bci,
1137 p2i(instr_pc), (stub_id == Runtime1::access_field_patching_id) ? "field" : "klass");
1138 nmethod* caller_code = CodeCache::find_nmethod(caller_frame.pc());
1139 assert(caller_code != NULL, "nmethod not found");
1140
1141 // NOTE we use pc() not original_pc() because we already know they are
1142 // identical otherwise we'd have never entered this block of code
1143
1144 const ImmutableOopMap* map = caller_code->oop_map_for_return_address(caller_frame.pc());
1145 assert(map != NULL, "null check");
1146 map->print();
1147 tty->cr();
1148
1149 Disassembler::decode(copy_buff, copy_buff + *byte_count, tty);
1150 }
1151 // depending on the code below, do_patch says whether to copy the patch body back into the nmethod
1152 bool do_patch = true;
1153 if (stub_id == Runtime1::access_field_patching_id) {
1154 // The offset may not be correct if the class was not loaded at code generation time.
1155 // Set it now.
1156 NativeMovRegMem* n_move = nativeMovRegMem_at(copy_buff);
1157 assert(n_move->offset() == 0 || (n_move->offset() == 4 && (patch_field_type == T_DOUBLE || patch_field_type == T_LONG)), "illegal offset for type");
1158 assert(patch_field_offset >= 0, "illegal offset");
1159 n_move->add_offset_in_bytes(patch_field_offset);
1160 } else if (load_klass_or_mirror_patch_id) {
1161 // If a getstatic or putstatic is referencing a klass which
1162 // isn't fully initialized, the patch body isn't copied into
1163 // place until initialization is complete. In this case the
1164 // patch site is setup so that any threads besides the
1165 // initializing thread are forced to come into the VM and
1166 // block.
1167 do_patch = (code != Bytecodes::_getstatic && code != Bytecodes::_putstatic) ||
1168 InstanceKlass::cast(init_klass)->is_initialized();
1169 NativeGeneralJump* jump = nativeGeneralJump_at(instr_pc);
1170 if (jump->jump_destination() == being_initialized_entry) {
1171 assert(do_patch == true, "initialization must be complete at this point");
1172 } else {
1173 // patch the instruction <move reg, klass>
1174 NativeMovConstReg* n_copy = nativeMovConstReg_at(copy_buff);
1175
1176 assert(n_copy->data() == 0 ||
1177 n_copy->data() == (intptr_t)Universe::non_oop_word(),
1178 "illegal init value");
1179 if (stub_id == Runtime1::load_klass_patching_id) {
1180 assert(load_klass != NULL, "klass not set");
1181 n_copy->set_data((intx) (load_klass));
1182 } else {
1183 // Don't need a G1 pre-barrier here since we assert above that data isn't an oop.
1184 n_copy->set_data(cast_from_oop<intx>(mirror()));
1185 }
1186
1187 if (TracePatching) {
1188 Disassembler::decode(copy_buff, copy_buff + *byte_count, tty);
1189 }
1190 }
1191 } else if (stub_id == Runtime1::load_appendix_patching_id) {
1192 NativeMovConstReg* n_copy = nativeMovConstReg_at(copy_buff);
1193 assert(n_copy->data() == 0 ||
1194 n_copy->data() == (intptr_t)Universe::non_oop_word(),
1195 "illegal init value");
1196 n_copy->set_data(cast_from_oop<intx>(appendix()));
1197
1198 if (TracePatching) {
1199 Disassembler::decode(copy_buff, copy_buff + *byte_count, tty);
1200 }
1201 } else {
1202 ShouldNotReachHere();
1203 }
1204
1205 if (do_patch) {
1206 // replace instructions
1207 // first replace the tail, then the call
1208 #ifdef ARM
1209 if((load_klass_or_mirror_patch_id ||
1210 stub_id == Runtime1::load_appendix_patching_id) &&
1211 nativeMovConstReg_at(copy_buff)->is_pc_relative()) {
1212 nmethod* nm = CodeCache::find_nmethod(instr_pc);
1213 address addr = NULL;
1214 assert(nm != NULL, "invalid nmethod_pc");
1215 RelocIterator mds(nm, copy_buff, copy_buff + 1);
1216 while (mds.next()) {
1217 if (mds.type() == relocInfo::oop_type) {
1218 assert(stub_id == Runtime1::load_mirror_patching_id ||
1219 stub_id == Runtime1::load_appendix_patching_id, "wrong stub id");
1220 oop_Relocation* r = mds.oop_reloc();
1221 addr = (address)r->oop_addr();
1222 break;
1223 } else if (mds.type() == relocInfo::metadata_type) {
1224 assert(stub_id == Runtime1::load_klass_patching_id, "wrong stub id");
1225 metadata_Relocation* r = mds.metadata_reloc();
1226 addr = (address)r->metadata_addr();
1227 break;
1228 }
1229 }
1230 assert(addr != NULL, "metadata relocation must exist");
1231 copy_buff -= *byte_count;
1232 NativeMovConstReg* n_copy2 = nativeMovConstReg_at(copy_buff);
1233 n_copy2->set_pc_relative_offset(addr, instr_pc);
1234 }
1235 #endif
1236
1237 for (int i = NativeGeneralJump::instruction_size; i < *byte_count; i++) {
1238 address ptr = copy_buff + i;
1239 int a_byte = (*ptr) & 0xFF;
1240 address dst = instr_pc + i;
1241 *(unsigned char*)dst = (unsigned char) a_byte;
1242 }
1243 ICache::invalidate_range(instr_pc, *byte_count);
1244 NativeGeneralJump::replace_mt_safe(instr_pc, copy_buff);
1245
1246 if (load_klass_or_mirror_patch_id ||
1247 stub_id == Runtime1::load_appendix_patching_id) {
1248 relocInfo::relocType rtype =
1249 (stub_id == Runtime1::load_klass_patching_id) ?
1250 relocInfo::metadata_type :
1251 relocInfo::oop_type;
1252 // update relocInfo to metadata
1253 nmethod* nm = CodeCache::find_nmethod(instr_pc);
1254 assert(nm != NULL, "invalid nmethod_pc");
1255
1256 // The old patch site is now a move instruction so update
1257 // the reloc info so that it will get updated during
1258 // future GCs.
1259 RelocIterator iter(nm, (address)instr_pc, (address)(instr_pc + 1));
1260 relocInfo::change_reloc_info_for_address(&iter, (address) instr_pc,
1261 relocInfo::none, rtype);
1262 }
1263
1264 } else {
1265 ICache::invalidate_range(copy_buff, *byte_count);
1266 NativeGeneralJump::insert_unconditional(instr_pc, being_initialized_entry);
1267 }
1268 }
1269 }
1270 }
1271
1272 // If we are patching in a non-perm oop, make sure the nmethod
1273 // is on the right list.
1274 {
1275 MutexLocker ml_code (current, CodeCache_lock, Mutex::_no_safepoint_check_flag);
1276 nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
1277 guarantee(nm != NULL, "only nmethods can contain non-perm oops");
1278
1279 // Since we've patched some oops in the nmethod,
1280 // (re)register it with the heap.
1281 Universe::heap()->register_nmethod(nm);
1282 }
1283 JRT_END
1284
1285 #else // DEOPTIMIZE_WHEN_PATCHING
1286
1287 void Runtime1::patch_code(JavaThread* current, Runtime1::StubID stub_id) {
1288 #ifndef PRODUCT
1289 if (PrintC1Statistics) {
1290 _patch_code_slowcase_cnt++;
1291 }
1292 #endif
1293
1294 // Enable WXWrite: the function is called by c1 stub as a runtime function
1295 // (see another implementation above).
1296 MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, current));
1297
1298 if (TracePatching) {
1299 tty->print_cr("Deoptimizing because patch is needed");
1300 }
1301
1302 RegisterMap reg_map(current,
1303 RegisterMap::UpdateMap::skip,
1304 RegisterMap::ProcessFrames::include,
1305 RegisterMap::WalkContinuation::skip);
1306
1307 frame runtime_frame = current->last_frame();
1308 frame caller_frame = runtime_frame.sender(®_map);
1309 assert(caller_frame.is_compiled_frame(), "Wrong frame type");
1310
1311 // Make sure the nmethod is invalidated, i.e. made not entrant.
1312 nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
1313 if (nm != NULL) {
1314 nm->make_not_entrant();
1315 }
1316
1317 Deoptimization::deoptimize_frame(current, caller_frame.id());
1318 // Return to the now deoptimized frame.
1319 postcond(caller_is_deopted(current));
1320 }
1321
1322 #endif // DEOPTIMIZE_WHEN_PATCHING
1323
1324 // Entry point for compiled code. We want to patch a nmethod.
1325 // We don't do a normal VM transition here because we want to
1326 // know after the patching is complete and any safepoint(s) are taken
1327 // if the calling nmethod was deoptimized. We do this by calling a
1328 // helper method which does the normal VM transition and when it
1329 // completes we can check for deoptimization. This simplifies the
1330 // assembly code in the cpu directories.
1331 //
1332 int Runtime1::move_klass_patching(JavaThread* current) {
1333 //
1334 // NOTE: we are still in Java
1335 //
1336 debug_only(NoHandleMark nhm;)
1337 {
1338 // Enter VM mode
1339 ResetNoHandleMark rnhm;
1340 patch_code(current, load_klass_patching_id);
1341 }
1342 // Back in JAVA, use no oops DON'T safepoint
1343
1344 // Return true if calling code is deoptimized
1345
1346 return caller_is_deopted(current);
1347 }
1348
1349 int Runtime1::move_mirror_patching(JavaThread* current) {
1350 //
1351 // NOTE: we are still in Java
1352 //
1353 debug_only(NoHandleMark nhm;)
1354 {
1355 // Enter VM mode
1356 ResetNoHandleMark rnhm;
1357 patch_code(current, load_mirror_patching_id);
1358 }
1359 // Back in JAVA, use no oops DON'T safepoint
1360
1361 // Return true if calling code is deoptimized
1362
1363 return caller_is_deopted(current);
1364 }
1365
1366 int Runtime1::move_appendix_patching(JavaThread* current) {
1367 //
1368 // NOTE: we are still in Java
1369 //
1370 debug_only(NoHandleMark nhm;)
1371 {
1372 // Enter VM mode
1373 ResetNoHandleMark rnhm;
1374 patch_code(current, load_appendix_patching_id);
1375 }
1376 // Back in JAVA, use no oops DON'T safepoint
1377
1378 // Return true if calling code is deoptimized
1379
1380 return caller_is_deopted(current);
1381 }
1382
1383 // Entry point for compiled code. We want to patch a nmethod.
1384 // We don't do a normal VM transition here because we want to
1385 // know after the patching is complete and any safepoint(s) are taken
1386 // if the calling nmethod was deoptimized. We do this by calling a
1387 // helper method which does the normal VM transition and when it
1388 // completes we can check for deoptimization. This simplifies the
1389 // assembly code in the cpu directories.
1390 //
1391 int Runtime1::access_field_patching(JavaThread* current) {
1392 //
1393 // NOTE: we are still in Java
1394 //
1395 // Handles created in this function will be deleted by the
1396 // HandleMarkCleaner in the transition to the VM.
1397 NoHandleMark nhm;
1398 {
1399 // Enter VM mode
1400 ResetNoHandleMark rnhm;
1401 patch_code(current, access_field_patching_id);
1402 }
1403 // Back in JAVA, use no oops DON'T safepoint
1404
1405 // Return true if calling code is deoptimized
1406
1407 return caller_is_deopted(current);
1408 }
1409
1410
1411 JRT_LEAF(void, Runtime1::trace_block_entry(jint block_id))
1412 // for now we just print out the block id
1413 tty->print("%d ", block_id);
1414 JRT_END
1415
1416
1417 JRT_LEAF(int, Runtime1::is_instance_of(oopDesc* mirror, oopDesc* obj))
1418 // had to return int instead of bool, otherwise there may be a mismatch
1419 // between the C calling convention and the Java one.
1420 // e.g., on x86, GCC may clear only %al when returning a bool false, but
1421 // JVM takes the whole %eax as the return value, which may misinterpret
1422 // the return value as a boolean true.
1423
1424 assert(mirror != NULL, "should null-check on mirror before calling");
1425 Klass* k = java_lang_Class::as_Klass(mirror);
1426 return (k != NULL && obj != NULL && obj->is_a(k)) ? 1 : 0;
1427 JRT_END
1428
1429 JRT_ENTRY(void, Runtime1::predicate_failed_trap(JavaThread* current))
1430 ResourceMark rm;
1431
1432 RegisterMap reg_map(current,
1433 RegisterMap::UpdateMap::skip,
1434 RegisterMap::ProcessFrames::include,
1435 RegisterMap::WalkContinuation::skip);
1436 frame runtime_frame = current->last_frame();
1437 frame caller_frame = runtime_frame.sender(®_map);
1438
1439 nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
1440 assert (nm != NULL, "no more nmethod?");
1441 nm->make_not_entrant();
1442
1443 methodHandle m(current, nm->method());
1444 MethodData* mdo = m->method_data();
1445
1446 if (mdo == NULL && !HAS_PENDING_EXCEPTION) {
1447 // Build an MDO. Ignore errors like OutOfMemory;
1448 // that simply means we won't have an MDO to update.
1449 Method::build_profiling_method_data(m, THREAD);
1450 if (HAS_PENDING_EXCEPTION) {
1451 // Only metaspace OOM is expected. No Java code executed.
1452 assert((PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())), "we expect only an OOM error here");
1453 CLEAR_PENDING_EXCEPTION;
1454 }
1455 mdo = m->method_data();
1456 }
1457
1458 if (mdo != NULL) {
1459 mdo->inc_trap_count(Deoptimization::Reason_none);
1460 }
1461
1462 if (TracePredicateFailedTraps) {
1463 stringStream ss1, ss2;
1464 vframeStream vfst(current);
1465 Method* inlinee = vfst.method();
1466 inlinee->print_short_name(&ss1);
1467 m->print_short_name(&ss2);
1468 tty->print_cr("Predicate failed trap in method %s at bci %d inlined in %s at pc " INTPTR_FORMAT, ss1.as_string(), vfst.bci(), ss2.as_string(), p2i(caller_frame.pc()));
1469 }
1470
1471
1472 Deoptimization::deoptimize_frame(current, caller_frame.id());
1473
1474 JRT_END
1475
1476 #ifndef PRODUCT
1477 void Runtime1::print_statistics() {
1478 tty->print_cr("C1 Runtime statistics:");
1479 tty->print_cr(" _resolve_invoke_virtual_cnt: %d", SharedRuntime::_resolve_virtual_ctr);
1480 tty->print_cr(" _resolve_invoke_opt_virtual_cnt: %d", SharedRuntime::_resolve_opt_virtual_ctr);
1481 tty->print_cr(" _resolve_invoke_static_cnt: %d", SharedRuntime::_resolve_static_ctr);
1482 tty->print_cr(" _handle_wrong_method_cnt: %d", SharedRuntime::_wrong_method_ctr);
1483 tty->print_cr(" _ic_miss_cnt: %d", SharedRuntime::_ic_miss_ctr);
1484 tty->print_cr(" _generic_arraycopystub_cnt: %d", _generic_arraycopystub_cnt);
1485 tty->print_cr(" _byte_arraycopy_cnt: %d", _byte_arraycopy_stub_cnt);
1486 tty->print_cr(" _short_arraycopy_cnt: %d", _short_arraycopy_stub_cnt);
1487 tty->print_cr(" _int_arraycopy_cnt: %d", _int_arraycopy_stub_cnt);
1488 tty->print_cr(" _long_arraycopy_cnt: %d", _long_arraycopy_stub_cnt);
1489 tty->print_cr(" _oop_arraycopy_cnt: %d", _oop_arraycopy_stub_cnt);
1490 tty->print_cr(" _arraycopy_slowcase_cnt: %d", _arraycopy_slowcase_cnt);
1491 tty->print_cr(" _arraycopy_checkcast_cnt: %d", _arraycopy_checkcast_cnt);
1492 tty->print_cr(" _arraycopy_checkcast_attempt_cnt:%d", _arraycopy_checkcast_attempt_cnt);
1493
1494 tty->print_cr(" _new_type_array_slowcase_cnt: %d", _new_type_array_slowcase_cnt);
1495 tty->print_cr(" _new_object_array_slowcase_cnt: %d", _new_object_array_slowcase_cnt);
1496 tty->print_cr(" _new_instance_slowcase_cnt: %d", _new_instance_slowcase_cnt);
1497 tty->print_cr(" _new_multi_array_slowcase_cnt: %d", _new_multi_array_slowcase_cnt);
1498 tty->print_cr(" _monitorenter_slowcase_cnt: %d", _monitorenter_slowcase_cnt);
1499 tty->print_cr(" _monitorexit_slowcase_cnt: %d", _monitorexit_slowcase_cnt);
1500 tty->print_cr(" _patch_code_slowcase_cnt: %d", _patch_code_slowcase_cnt);
1501
1502 tty->print_cr(" _throw_range_check_exception_count: %d:", _throw_range_check_exception_count);
1503 tty->print_cr(" _throw_index_exception_count: %d:", _throw_index_exception_count);
1504 tty->print_cr(" _throw_div0_exception_count: %d:", _throw_div0_exception_count);
1505 tty->print_cr(" _throw_null_pointer_exception_count: %d:", _throw_null_pointer_exception_count);
1506 tty->print_cr(" _throw_class_cast_exception_count: %d:", _throw_class_cast_exception_count);
1507 tty->print_cr(" _throw_incompatible_class_change_error_count: %d:", _throw_incompatible_class_change_error_count);
1508 tty->print_cr(" _throw_count: %d:", _throw_count);
1509
1510 SharedRuntime::print_ic_miss_histogram();
1511 tty->cr();
1512 }
1513 #endif // PRODUCT
--- EOF ---