1 /* 2 * Copyright (c) 1999, 2023, 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 #include "utilities/macros.hpp" 77 78 79 // Implementation of StubAssembler 80 81 StubAssembler::StubAssembler(CodeBuffer* code, const char * name, int stub_id) : C1_MacroAssembler(code) { 82 _name = name; 83 _must_gc_arguments = false; 84 _frame_size = no_frame_size; 85 _num_rt_args = 0; 86 _stub_id = stub_id; 87 } 88 89 90 void StubAssembler::set_info(const char* name, bool must_gc_arguments) { 91 _name = name; 92 _must_gc_arguments = must_gc_arguments; 93 } 94 95 96 void StubAssembler::set_frame_size(int size) { 97 if (_frame_size == no_frame_size) { 98 _frame_size = size; 99 } 100 assert(_frame_size == size, "can't change the frame size"); 101 } 102 103 104 void StubAssembler::set_num_rt_args(int args) { 105 if (_num_rt_args == 0) { 106 _num_rt_args = args; 107 } 108 assert(_num_rt_args == args, "can't change the number of args"); 109 } 110 111 // Implementation of Runtime1 112 113 CodeBlob* Runtime1::_blobs[Runtime1::number_of_ids]; 114 const char *Runtime1::_blob_names[] = { 115 RUNTIME1_STUBS(STUB_NAME, LAST_STUB_NAME) 116 }; 117 118 #ifndef PRODUCT 119 // statistics 120 uint Runtime1::_generic_arraycopystub_cnt = 0; 121 uint Runtime1::_arraycopy_slowcase_cnt = 0; 122 uint Runtime1::_arraycopy_checkcast_cnt = 0; 123 uint Runtime1::_arraycopy_checkcast_attempt_cnt = 0; 124 uint Runtime1::_new_type_array_slowcase_cnt = 0; 125 uint Runtime1::_new_object_array_slowcase_cnt = 0; 126 uint Runtime1::_new_instance_slowcase_cnt = 0; 127 uint Runtime1::_new_multi_array_slowcase_cnt = 0; 128 uint Runtime1::_monitorenter_slowcase_cnt = 0; 129 uint Runtime1::_monitorexit_slowcase_cnt = 0; 130 uint Runtime1::_patch_code_slowcase_cnt = 0; 131 uint Runtime1::_throw_range_check_exception_count = 0; 132 uint Runtime1::_throw_index_exception_count = 0; 133 uint Runtime1::_throw_div0_exception_count = 0; 134 uint Runtime1::_throw_null_pointer_exception_count = 0; 135 uint Runtime1::_throw_class_cast_exception_count = 0; 136 uint Runtime1::_throw_incompatible_class_change_error_count = 0; 137 uint Runtime1::_throw_count = 0; 138 139 static uint _byte_arraycopy_stub_cnt = 0; 140 static uint _short_arraycopy_stub_cnt = 0; 141 static uint _int_arraycopy_stub_cnt = 0; 142 static uint _long_arraycopy_stub_cnt = 0; 143 static uint _oop_arraycopy_stub_cnt = 0; 144 145 address Runtime1::arraycopy_count_address(BasicType type) { 146 switch (type) { 147 case T_BOOLEAN: 148 case T_BYTE: return (address)&_byte_arraycopy_stub_cnt; 149 case T_CHAR: 150 case T_SHORT: return (address)&_short_arraycopy_stub_cnt; 151 case T_FLOAT: 152 case T_INT: return (address)&_int_arraycopy_stub_cnt; 153 case T_DOUBLE: 154 case T_LONG: return (address)&_long_arraycopy_stub_cnt; 155 case T_ARRAY: 156 case T_OBJECT: return (address)&_oop_arraycopy_stub_cnt; 157 default: 158 ShouldNotReachHere(); 159 return nullptr; 160 } 161 } 162 163 164 #endif 165 166 // Simple helper to see if the caller of a runtime stub which 167 // entered the VM has been deoptimized 168 169 static bool caller_is_deopted(JavaThread* current) { 170 RegisterMap reg_map(current, 171 RegisterMap::UpdateMap::skip, 172 RegisterMap::ProcessFrames::include, 173 RegisterMap::WalkContinuation::skip); 174 frame runtime_frame = current->last_frame(); 175 frame caller_frame = runtime_frame.sender(®_map); 176 assert(caller_frame.is_compiled_frame(), "must be compiled"); 177 return caller_frame.is_deoptimized_frame(); 178 } 179 180 // Stress deoptimization 181 static void deopt_caller(JavaThread* current) { 182 if (!caller_is_deopted(current)) { 183 RegisterMap reg_map(current, 184 RegisterMap::UpdateMap::skip, 185 RegisterMap::ProcessFrames::include, 186 RegisterMap::WalkContinuation::skip); 187 frame runtime_frame = current->last_frame(); 188 frame caller_frame = runtime_frame.sender(®_map); 189 Deoptimization::deoptimize_frame(current, caller_frame.id()); 190 assert(caller_is_deopted(current), "Must be deoptimized"); 191 } 192 } 193 194 class StubIDStubAssemblerCodeGenClosure: public StubAssemblerCodeGenClosure { 195 private: 196 Runtime1::StubID _id; 197 public: 198 StubIDStubAssemblerCodeGenClosure(Runtime1::StubID id) : _id(id) {} 199 virtual OopMapSet* generate_code(StubAssembler* sasm) { 200 return Runtime1::generate_code_for(_id, sasm); 201 } 202 }; 203 204 CodeBlob* Runtime1::generate_blob(BufferBlob* buffer_blob, int stub_id, const char* name, bool expect_oop_map, StubAssemblerCodeGenClosure* cl) { 205 ResourceMark rm; 206 // create code buffer for code storage 207 CodeBuffer code(buffer_blob); 208 209 OopMapSet* oop_maps; 210 int frame_size; 211 bool must_gc_arguments; 212 213 Compilation::setup_code_buffer(&code, 0); 214 215 // create assembler for code generation 216 StubAssembler* sasm = new StubAssembler(&code, name, stub_id); 217 // generate code for runtime stub 218 oop_maps = cl->generate_code(sasm); 219 assert(oop_maps == nullptr || sasm->frame_size() != no_frame_size, 220 "if stub has an oop map it must have a valid frame size"); 221 assert(!expect_oop_map || oop_maps != nullptr, "must have an oopmap"); 222 223 // align so printing shows nop's instead of random code at the end (SimpleStubs are aligned) 224 sasm->align(BytesPerWord); 225 // make sure all code is in code buffer 226 sasm->flush(); 227 228 frame_size = sasm->frame_size(); 229 must_gc_arguments = sasm->must_gc_arguments(); 230 // create blob - distinguish a few special cases 231 CodeBlob* blob = RuntimeStub::new_runtime_stub(name, 232 &code, 233 CodeOffsets::frame_never_safe, 234 frame_size, 235 oop_maps, 236 must_gc_arguments); 237 assert(blob != nullptr, "blob must exist"); 238 return blob; 239 } 240 241 void Runtime1::generate_blob_for(BufferBlob* buffer_blob, StubID id) { 242 assert(0 <= id && id < number_of_ids, "illegal stub id"); 243 bool expect_oop_map = true; 244 #ifdef ASSERT 245 // Make sure that stubs that need oopmaps have them 246 switch (id) { 247 // These stubs don't need to have an oopmap 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() != nullptr) { 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 346 #undef FUNCTION_CASE 347 348 // Soft float adds more runtime names. 349 return pd_name_for_address(entry); 350 } 351 352 353 JRT_ENTRY(void, Runtime1::new_instance(JavaThread* current, Klass* klass)) 354 #ifndef PRODUCT 355 if (PrintC1Statistics) { 356 _new_instance_slowcase_cnt++; 357 } 358 #endif 359 assert(klass->is_klass(), "not a class"); 360 Handle holder(current, klass->klass_holder()); // keep the klass alive 361 InstanceKlass* h = InstanceKlass::cast(klass); 362 h->check_valid_for_instantiation(true, CHECK); 363 // make sure klass is initialized 364 h->initialize(CHECK); 365 // allocate instance and return via TLS 366 oop obj = h->allocate_instance(CHECK); 367 current->set_vm_result(obj); 368 JRT_END 369 370 371 JRT_ENTRY(void, Runtime1::new_type_array(JavaThread* current, Klass* klass, jint length)) 372 #ifndef PRODUCT 373 if (PrintC1Statistics) { 374 _new_type_array_slowcase_cnt++; 375 } 376 #endif 377 // Note: no handle for klass needed since they are not used 378 // anymore after new_typeArray() and no GC can happen before. 379 // (This may have to change if this code changes!) 380 assert(klass->is_klass(), "not a class"); 381 BasicType elt_type = TypeArrayKlass::cast(klass)->element_type(); 382 oop obj = oopFactory::new_typeArray(elt_type, length, CHECK); 383 current->set_vm_result(obj); 384 // This is pretty rare but this runtime patch is stressful to deoptimization 385 // if we deoptimize here so force a deopt to stress the path. 386 if (DeoptimizeALot) { 387 deopt_caller(current); 388 } 389 390 JRT_END 391 392 393 JRT_ENTRY(void, Runtime1::new_object_array(JavaThread* current, Klass* array_klass, jint length)) 394 #ifndef PRODUCT 395 if (PrintC1Statistics) { 396 _new_object_array_slowcase_cnt++; 397 } 398 #endif 399 // Note: no handle for klass needed since they are not used 400 // anymore after new_objArray() and no GC can happen before. 401 // (This may have to change if this code changes!) 402 assert(array_klass->is_klass(), "not a class"); 403 Handle holder(current, array_klass->klass_holder()); // keep the klass alive 404 Klass* elem_klass = ObjArrayKlass::cast(array_klass)->element_klass(); 405 objArrayOop obj = oopFactory::new_objArray(elem_klass, length, CHECK); 406 current->set_vm_result(obj); 407 // This is pretty rare but this runtime patch is stressful to deoptimization 408 // if we deoptimize here so force a deopt to stress the path. 409 if (DeoptimizeALot) { 410 deopt_caller(current); 411 } 412 JRT_END 413 414 415 JRT_ENTRY(void, Runtime1::new_multi_array(JavaThread* current, Klass* klass, int rank, jint* dims)) 416 #ifndef PRODUCT 417 if (PrintC1Statistics) { 418 _new_multi_array_slowcase_cnt++; 419 } 420 #endif 421 assert(klass->is_klass(), "not a class"); 422 assert(rank >= 1, "rank must be nonzero"); 423 Handle holder(current, klass->klass_holder()); // keep the klass alive 424 oop obj = ArrayKlass::cast(klass)->multi_allocate(rank, dims, CHECK); 425 current->set_vm_result(obj); 426 JRT_END 427 428 429 JRT_ENTRY(void, Runtime1::unimplemented_entry(JavaThread* current, StubID id)) 430 tty->print_cr("Runtime1::entry_for(%d) returned unimplemented entry point", id); 431 JRT_END 432 433 434 JRT_ENTRY(void, Runtime1::throw_array_store_exception(JavaThread* current, oopDesc* obj)) 435 ResourceMark rm(current); 436 const char* klass_name = obj->klass()->external_name(); 437 SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ArrayStoreException(), klass_name); 438 JRT_END 439 440 441 // counter_overflow() is called from within C1-compiled methods. The enclosing method is the method 442 // associated with the top activation record. The inlinee (that is possibly included in the enclosing 443 // method) method is passed as an argument. In order to do that it is embedded in the code as 444 // a constant. 445 static nmethod* counter_overflow_helper(JavaThread* current, int branch_bci, Method* m) { 446 nmethod* osr_nm = nullptr; 447 methodHandle method(current, m); 448 449 RegisterMap map(current, 450 RegisterMap::UpdateMap::skip, 451 RegisterMap::ProcessFrames::include, 452 RegisterMap::WalkContinuation::skip); 453 frame fr = current->last_frame().sender(&map); 454 nmethod* nm = (nmethod*) fr.cb(); 455 assert(nm!= nullptr && nm->is_nmethod(), "Sanity check"); 456 methodHandle enclosing_method(current, nm->method()); 457 458 CompLevel level = (CompLevel)nm->comp_level(); 459 int bci = InvocationEntryBci; 460 if (branch_bci != InvocationEntryBci) { 461 // Compute destination bci 462 address pc = method()->code_base() + branch_bci; 463 Bytecodes::Code branch = Bytecodes::code_at(method(), pc); 464 int offset = 0; 465 switch (branch) { 466 case Bytecodes::_if_icmplt: case Bytecodes::_iflt: 467 case Bytecodes::_if_icmpgt: case Bytecodes::_ifgt: 468 case Bytecodes::_if_icmple: case Bytecodes::_ifle: 469 case Bytecodes::_if_icmpge: case Bytecodes::_ifge: 470 case Bytecodes::_if_icmpeq: case Bytecodes::_if_acmpeq: case Bytecodes::_ifeq: 471 case Bytecodes::_if_icmpne: case Bytecodes::_if_acmpne: case Bytecodes::_ifne: 472 case Bytecodes::_ifnull: case Bytecodes::_ifnonnull: case Bytecodes::_goto: 473 offset = (int16_t)Bytes::get_Java_u2(pc + 1); 474 break; 475 case Bytecodes::_goto_w: 476 offset = Bytes::get_Java_u4(pc + 1); 477 break; 478 default: ; 479 } 480 bci = branch_bci + offset; 481 } 482 osr_nm = CompilationPolicy::event(enclosing_method, method, branch_bci, bci, level, nm, current); 483 return osr_nm; 484 } 485 486 JRT_BLOCK_ENTRY(address, Runtime1::counter_overflow(JavaThread* current, int bci, Method* method)) 487 nmethod* osr_nm; 488 JRT_BLOCK 489 osr_nm = counter_overflow_helper(current, bci, method); 490 if (osr_nm != nullptr) { 491 RegisterMap map(current, 492 RegisterMap::UpdateMap::skip, 493 RegisterMap::ProcessFrames::include, 494 RegisterMap::WalkContinuation::skip); 495 frame fr = current->last_frame().sender(&map); 496 Deoptimization::deoptimize_frame(current, fr.id()); 497 } 498 JRT_BLOCK_END 499 return nullptr; 500 JRT_END 501 502 extern void vm_exit(int code); 503 504 // Enter this method from compiled code handler below. This is where we transition 505 // to VM mode. This is done as a helper routine so that the method called directly 506 // from compiled code does not have to transition to VM. This allows the entry 507 // method to see if the nmethod that we have just looked up a handler for has 508 // been deoptimized while we were in the vm. This simplifies the assembly code 509 // cpu directories. 510 // 511 // We are entering here from exception stub (via the entry method below) 512 // If there is a compiled exception handler in this method, we will continue there; 513 // otherwise we will unwind the stack and continue at the caller of top frame method 514 // Note: we enter in Java using a special JRT wrapper. This wrapper allows us to 515 // control the area where we can allow a safepoint. After we exit the safepoint area we can 516 // check to see if the handler we are going to return is now in a nmethod that has 517 // been deoptimized. If that is the case we return the deopt blob 518 // unpack_with_exception entry instead. This makes life for the exception blob easier 519 // because making that same check and diverting is painful from assembly language. 520 JRT_ENTRY_NO_ASYNC(static address, exception_handler_for_pc_helper(JavaThread* current, oopDesc* ex, address pc, nmethod*& nm)) 521 // Reset method handle flag. 522 current->set_is_method_handle_return(false); 523 524 Handle exception(current, ex); 525 526 // This function is called when we are about to throw an exception. Therefore, 527 // we have to poll the stack watermark barrier to make sure that not yet safe 528 // stack frames are made safe before returning into them. 529 if (current->last_frame().cb() == Runtime1::blob_for(Runtime1::handle_exception_from_callee_id)) { 530 // The Runtime1::handle_exception_from_callee_id handler is invoked after the 531 // frame has been unwound. It instead builds its own stub frame, to call the 532 // runtime. But the throwing frame has already been unwound here. 533 StackWatermarkSet::after_unwind(current); 534 } 535 536 nm = CodeCache::find_nmethod(pc); 537 assert(nm != nullptr, "this is not an nmethod"); 538 // Adjust the pc as needed/ 539 if (nm->is_deopt_pc(pc)) { 540 RegisterMap map(current, 541 RegisterMap::UpdateMap::skip, 542 RegisterMap::ProcessFrames::include, 543 RegisterMap::WalkContinuation::skip); 544 frame exception_frame = current->last_frame().sender(&map); 545 // if the frame isn't deopted then pc must not correspond to the caller of last_frame 546 assert(exception_frame.is_deoptimized_frame(), "must be deopted"); 547 pc = exception_frame.pc(); 548 } 549 assert(exception.not_null(), "null exceptions should be handled by throw_exception"); 550 // Check that exception is a subclass of Throwable 551 assert(exception->is_a(vmClasses::Throwable_klass()), 552 "Exception not subclass of Throwable"); 553 554 // debugging support 555 // tracing 556 if (log_is_enabled(Info, exceptions)) { 557 ResourceMark rm; // print_value_string 558 stringStream tempst; 559 assert(nm->method() != nullptr, "Unexpected null method()"); 560 tempst.print("C1 compiled method <%s>\n" 561 " at PC" INTPTR_FORMAT " for thread " INTPTR_FORMAT, 562 nm->method()->print_value_string(), p2i(pc), p2i(current)); 563 Exceptions::log_exception(exception, tempst.freeze()); 564 } 565 // for AbortVMOnException flag 566 Exceptions::debug_check_abort(exception); 567 568 // Check the stack guard pages and re-enable them if necessary and there is 569 // enough space on the stack to do so. Use fast exceptions only if the guard 570 // pages are enabled. 571 bool guard_pages_enabled = current->stack_overflow_state()->reguard_stack_if_needed(); 572 573 if (JvmtiExport::can_post_on_exceptions()) { 574 // To ensure correct notification of exception catches and throws 575 // we have to deoptimize here. If we attempted to notify the 576 // catches and throws during this exception lookup it's possible 577 // we could deoptimize on the way out of the VM and end back in 578 // the interpreter at the throw site. This would result in double 579 // notifications since the interpreter would also notify about 580 // these same catches and throws as it unwound the frame. 581 582 RegisterMap reg_map(current, 583 RegisterMap::UpdateMap::include, 584 RegisterMap::ProcessFrames::include, 585 RegisterMap::WalkContinuation::skip); 586 frame stub_frame = current->last_frame(); 587 frame caller_frame = stub_frame.sender(®_map); 588 589 // We don't really want to deoptimize the nmethod itself since we 590 // can actually continue in the exception handler ourselves but I 591 // don't see an easy way to have the desired effect. 592 Deoptimization::deoptimize_frame(current, caller_frame.id()); 593 assert(caller_is_deopted(current), "Must be deoptimized"); 594 595 return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls(); 596 } 597 598 // ExceptionCache is used only for exceptions at call sites and not for implicit exceptions 599 if (guard_pages_enabled) { 600 address fast_continuation = nm->handler_for_exception_and_pc(exception, pc); 601 if (fast_continuation != nullptr) { 602 // Set flag if return address is a method handle call site. 603 current->set_is_method_handle_return(nm->is_method_handle_return(pc)); 604 return fast_continuation; 605 } 606 } 607 608 // If the stack guard pages are enabled, check whether there is a handler in 609 // the current method. Otherwise (guard pages disabled), force an unwind and 610 // skip the exception cache update (i.e., just leave continuation as null). 611 address continuation = nullptr; 612 if (guard_pages_enabled) { 613 614 // New exception handling mechanism can support inlined methods 615 // with exception handlers since the mappings are from PC to PC 616 617 // Clear out the exception oop and pc since looking up an 618 // exception handler can cause class loading, which might throw an 619 // exception and those fields are expected to be clear during 620 // normal bytecode execution. 621 current->clear_exception_oop_and_pc(); 622 623 bool recursive_exception = false; 624 continuation = SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, false, false, recursive_exception); 625 // If an exception was thrown during exception dispatch, the exception oop may have changed 626 current->set_exception_oop(exception()); 627 current->set_exception_pc(pc); 628 629 // the exception cache is used only by non-implicit exceptions 630 // Update the exception cache only when there didn't happen 631 // another exception during the computation of the compiled 632 // exception handler. Checking for exception oop equality is not 633 // sufficient because some exceptions are pre-allocated and reused. 634 if (continuation != nullptr && !recursive_exception) { 635 nm->add_handler_for_exception_and_pc(exception, pc, continuation); 636 } 637 } 638 639 current->set_vm_result(exception()); 640 // Set flag if return address is a method handle call site. 641 current->set_is_method_handle_return(nm->is_method_handle_return(pc)); 642 643 if (log_is_enabled(Info, exceptions)) { 644 ResourceMark rm; 645 log_info(exceptions)("Thread " PTR_FORMAT " continuing at PC " PTR_FORMAT 646 " for exception thrown at PC " PTR_FORMAT, 647 p2i(current), p2i(continuation), p2i(pc)); 648 } 649 650 return continuation; 651 JRT_END 652 653 // Enter this method from compiled code only if there is a Java exception handler 654 // in the method handling the exception. 655 // We are entering here from exception stub. We don't do a normal VM transition here. 656 // We do it in a helper. This is so we can check to see if the nmethod we have just 657 // searched for an exception handler has been deoptimized in the meantime. 658 address Runtime1::exception_handler_for_pc(JavaThread* current) { 659 oop exception = current->exception_oop(); 660 address pc = current->exception_pc(); 661 // Still in Java mode 662 DEBUG_ONLY(NoHandleMark nhm); 663 nmethod* nm = nullptr; 664 address continuation = nullptr; 665 { 666 // Enter VM mode by calling the helper 667 ResetNoHandleMark rnhm; 668 continuation = exception_handler_for_pc_helper(current, exception, pc, nm); 669 } 670 // Back in JAVA, use no oops DON'T safepoint 671 672 // Now check to see if the nmethod we were called from is now deoptimized. 673 // If so we must return to the deopt blob and deoptimize the nmethod 674 if (nm != nullptr && caller_is_deopted(current)) { 675 continuation = SharedRuntime::deopt_blob()->unpack_with_exception_in_tls(); 676 } 677 678 assert(continuation != nullptr, "no handler found"); 679 return continuation; 680 } 681 682 683 JRT_ENTRY(void, Runtime1::throw_range_check_exception(JavaThread* current, int index, arrayOopDesc* a)) 684 #ifndef PRODUCT 685 if (PrintC1Statistics) { 686 _throw_range_check_exception_count++; 687 } 688 #endif 689 const int len = 35; 690 assert(len < strlen("Index %d out of bounds for length %d"), "Must allocate more space for message."); 691 char message[2 * jintAsStringSize + len]; 692 os::snprintf_checked(message, sizeof(message), "Index %d out of bounds for length %d", index, a->length()); 693 SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), message); 694 JRT_END 695 696 697 JRT_ENTRY(void, Runtime1::throw_index_exception(JavaThread* current, int index)) 698 #ifndef PRODUCT 699 if (PrintC1Statistics) { 700 _throw_index_exception_count++; 701 } 702 #endif 703 char message[16]; 704 os::snprintf_checked(message, sizeof(message), "%d", index); 705 SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_IndexOutOfBoundsException(), message); 706 JRT_END 707 708 709 JRT_ENTRY(void, Runtime1::throw_div0_exception(JavaThread* current)) 710 #ifndef PRODUCT 711 if (PrintC1Statistics) { 712 _throw_div0_exception_count++; 713 } 714 #endif 715 SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ArithmeticException(), "/ by zero"); 716 JRT_END 717 718 719 JRT_ENTRY(void, Runtime1::throw_null_pointer_exception(JavaThread* current)) 720 #ifndef PRODUCT 721 if (PrintC1Statistics) { 722 _throw_null_pointer_exception_count++; 723 } 724 #endif 725 SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_NullPointerException()); 726 JRT_END 727 728 729 JRT_ENTRY(void, Runtime1::throw_class_cast_exception(JavaThread* current, oopDesc* object)) 730 #ifndef PRODUCT 731 if (PrintC1Statistics) { 732 _throw_class_cast_exception_count++; 733 } 734 #endif 735 ResourceMark rm(current); 736 char* message = SharedRuntime::generate_class_cast_message(current, object->klass()); 737 SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ClassCastException(), message); 738 JRT_END 739 740 741 JRT_ENTRY(void, Runtime1::throw_incompatible_class_change_error(JavaThread* current)) 742 #ifndef PRODUCT 743 if (PrintC1Statistics) { 744 _throw_incompatible_class_change_error_count++; 745 } 746 #endif 747 ResourceMark rm(current); 748 SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_IncompatibleClassChangeError()); 749 JRT_END 750 751 752 JRT_BLOCK_ENTRY(void, Runtime1::monitorenter(JavaThread* current, oopDesc* obj, BasicObjectLock* lock)) 753 #ifndef PRODUCT 754 if (PrintC1Statistics) { 755 _monitorenter_slowcase_cnt++; 756 } 757 #endif 758 if (LockingMode == LM_MONITOR) { 759 lock->set_obj(obj); 760 } 761 assert(obj == lock->obj(), "must match: " PTR_FORMAT, p2i(lock)); 762 SharedRuntime::monitor_enter_helper(obj, lock->lock(), current); 763 JRT_END 764 765 766 JRT_LEAF(void, Runtime1::monitorexit(JavaThread* current, BasicObjectLock* lock)) 767 assert(current == JavaThread::current(), "pre-condition"); 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 != nullptr, "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 != nullptr) { 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 = nullptr; // klass needed by load_klass_patching code 959 Klass* load_klass = nullptr; // klass needed by load_klass_patching code 960 Handle mirror(current, nullptr); // oop needed by load_mirror_patching code 961 Handle appendix(current, nullptr); // 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 = nullptr; 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 ResolvedMethodEntry* entry = pool->cache()->set_method_handle(index, info); 1059 appendix = Handle(current, pool->cache()->appendix_if_resolved(entry)); 1060 break; 1061 } 1062 case Bytecodes::_invokedynamic: { 1063 int indy_index = pool->decode_invokedynamic_index(index); 1064 appendix = Handle(current, pool->cache()->set_dynamic_call(info, indy_index)); 1065 break; 1066 } 1067 default: fatal("unexpected bytecode for load_appendix_patching_id"); 1068 } 1069 } else { 1070 ShouldNotReachHere(); 1071 } 1072 1073 if (deoptimize_for_volatile || deoptimize_for_atomic) { 1074 // At compile time we assumed the field wasn't volatile/atomic but after 1075 // loading it turns out it was volatile/atomic so we have to throw the 1076 // compiled code out and let it be regenerated. 1077 if (TracePatching) { 1078 if (deoptimize_for_volatile) { 1079 tty->print_cr("Deoptimizing for patching volatile field reference"); 1080 } 1081 if (deoptimize_for_atomic) { 1082 tty->print_cr("Deoptimizing for patching atomic field reference"); 1083 } 1084 } 1085 1086 // It's possible the nmethod was invalidated in the last 1087 // safepoint, but if it's still alive then make it not_entrant. 1088 nmethod* nm = CodeCache::find_nmethod(caller_frame.pc()); 1089 if (nm != nullptr) { 1090 nm->make_not_entrant(); 1091 } 1092 1093 Deoptimization::deoptimize_frame(current, caller_frame.id()); 1094 1095 // Return to the now deoptimized frame. 1096 } 1097 1098 // Now copy code back 1099 1100 { 1101 MutexLocker ml_patch (current, Patching_lock, Mutex::_no_safepoint_check_flag); 1102 // 1103 // Deoptimization may have happened while we waited for the lock. 1104 // In that case we don't bother to do any patching we just return 1105 // and let the deopt happen 1106 if (!caller_is_deopted(current)) { 1107 NativeGeneralJump* jump = nativeGeneralJump_at(caller_frame.pc()); 1108 address instr_pc = jump->jump_destination(); 1109 NativeInstruction* ni = nativeInstruction_at(instr_pc); 1110 if (ni->is_jump() ) { 1111 // the jump has not been patched yet 1112 // The jump destination is slow case and therefore not part of the stubs 1113 // (stubs are only for StaticCalls) 1114 1115 // format of buffer 1116 // .... 1117 // instr byte 0 <-- copy_buff 1118 // instr byte 1 1119 // .. 1120 // instr byte n-1 1121 // n 1122 // .... <-- call destination 1123 1124 address stub_location = caller_frame.pc() + PatchingStub::patch_info_offset(); 1125 unsigned char* byte_count = (unsigned char*) (stub_location - 1); 1126 unsigned char* byte_skip = (unsigned char*) (stub_location - 2); 1127 unsigned char* being_initialized_entry_offset = (unsigned char*) (stub_location - 3); 1128 address copy_buff = stub_location - *byte_skip - *byte_count; 1129 address being_initialized_entry = stub_location - *being_initialized_entry_offset; 1130 if (TracePatching) { 1131 ttyLocker ttyl; 1132 tty->print_cr(" Patching %s at bci %d at address " INTPTR_FORMAT " (%s)", Bytecodes::name(code), bci, 1133 p2i(instr_pc), (stub_id == Runtime1::access_field_patching_id) ? "field" : "klass"); 1134 nmethod* caller_code = CodeCache::find_nmethod(caller_frame.pc()); 1135 assert(caller_code != nullptr, "nmethod not found"); 1136 1137 // NOTE we use pc() not original_pc() because we already know they are 1138 // identical otherwise we'd have never entered this block of code 1139 1140 const ImmutableOopMap* map = caller_code->oop_map_for_return_address(caller_frame.pc()); 1141 assert(map != nullptr, "null check"); 1142 map->print(); 1143 tty->cr(); 1144 1145 Disassembler::decode(copy_buff, copy_buff + *byte_count, tty); 1146 } 1147 // depending on the code below, do_patch says whether to copy the patch body back into the nmethod 1148 bool do_patch = true; 1149 if (stub_id == Runtime1::access_field_patching_id) { 1150 // The offset may not be correct if the class was not loaded at code generation time. 1151 // Set it now. 1152 NativeMovRegMem* n_move = nativeMovRegMem_at(copy_buff); 1153 assert(n_move->offset() == 0 || (n_move->offset() == 4 && (patch_field_type == T_DOUBLE || patch_field_type == T_LONG)), "illegal offset for type"); 1154 assert(patch_field_offset >= 0, "illegal offset"); 1155 n_move->add_offset_in_bytes(patch_field_offset); 1156 } else if (load_klass_or_mirror_patch_id) { 1157 // If a getstatic or putstatic is referencing a klass which 1158 // isn't fully initialized, the patch body isn't copied into 1159 // place until initialization is complete. In this case the 1160 // patch site is setup so that any threads besides the 1161 // initializing thread are forced to come into the VM and 1162 // block. 1163 do_patch = (code != Bytecodes::_getstatic && code != Bytecodes::_putstatic) || 1164 InstanceKlass::cast(init_klass)->is_initialized(); 1165 NativeGeneralJump* jump = nativeGeneralJump_at(instr_pc); 1166 if (jump->jump_destination() == being_initialized_entry) { 1167 assert(do_patch == true, "initialization must be complete at this point"); 1168 } else { 1169 // patch the instruction <move reg, klass> 1170 NativeMovConstReg* n_copy = nativeMovConstReg_at(copy_buff); 1171 1172 assert(n_copy->data() == 0 || 1173 n_copy->data() == (intptr_t)Universe::non_oop_word(), 1174 "illegal init value"); 1175 if (stub_id == Runtime1::load_klass_patching_id) { 1176 assert(load_klass != nullptr, "klass not set"); 1177 n_copy->set_data((intx) (load_klass)); 1178 } else { 1179 // Don't need a G1 pre-barrier here since we assert above that data isn't an oop. 1180 n_copy->set_data(cast_from_oop<intx>(mirror())); 1181 } 1182 1183 if (TracePatching) { 1184 Disassembler::decode(copy_buff, copy_buff + *byte_count, tty); 1185 } 1186 } 1187 } else if (stub_id == Runtime1::load_appendix_patching_id) { 1188 NativeMovConstReg* n_copy = nativeMovConstReg_at(copy_buff); 1189 assert(n_copy->data() == 0 || 1190 n_copy->data() == (intptr_t)Universe::non_oop_word(), 1191 "illegal init value"); 1192 n_copy->set_data(cast_from_oop<intx>(appendix())); 1193 1194 if (TracePatching) { 1195 Disassembler::decode(copy_buff, copy_buff + *byte_count, tty); 1196 } 1197 } else { 1198 ShouldNotReachHere(); 1199 } 1200 1201 if (do_patch) { 1202 // replace instructions 1203 // first replace the tail, then the call 1204 #ifdef ARM 1205 if((load_klass_or_mirror_patch_id || 1206 stub_id == Runtime1::load_appendix_patching_id) && 1207 nativeMovConstReg_at(copy_buff)->is_pc_relative()) { 1208 nmethod* nm = CodeCache::find_nmethod(instr_pc); 1209 address addr = nullptr; 1210 assert(nm != nullptr, "invalid nmethod_pc"); 1211 RelocIterator mds(nm, copy_buff, copy_buff + 1); 1212 while (mds.next()) { 1213 if (mds.type() == relocInfo::oop_type) { 1214 assert(stub_id == Runtime1::load_mirror_patching_id || 1215 stub_id == Runtime1::load_appendix_patching_id, "wrong stub id"); 1216 oop_Relocation* r = mds.oop_reloc(); 1217 addr = (address)r->oop_addr(); 1218 break; 1219 } else if (mds.type() == relocInfo::metadata_type) { 1220 assert(stub_id == Runtime1::load_klass_patching_id, "wrong stub id"); 1221 metadata_Relocation* r = mds.metadata_reloc(); 1222 addr = (address)r->metadata_addr(); 1223 break; 1224 } 1225 } 1226 assert(addr != nullptr, "metadata relocation must exist"); 1227 copy_buff -= *byte_count; 1228 NativeMovConstReg* n_copy2 = nativeMovConstReg_at(copy_buff); 1229 n_copy2->set_pc_relative_offset(addr, instr_pc); 1230 } 1231 #endif 1232 1233 for (int i = NativeGeneralJump::instruction_size; i < *byte_count; i++) { 1234 address ptr = copy_buff + i; 1235 int a_byte = (*ptr) & 0xFF; 1236 address dst = instr_pc + i; 1237 *(unsigned char*)dst = (unsigned char) a_byte; 1238 } 1239 ICache::invalidate_range(instr_pc, *byte_count); 1240 NativeGeneralJump::replace_mt_safe(instr_pc, copy_buff); 1241 1242 if (load_klass_or_mirror_patch_id || 1243 stub_id == Runtime1::load_appendix_patching_id) { 1244 relocInfo::relocType rtype = 1245 (stub_id == Runtime1::load_klass_patching_id) ? 1246 relocInfo::metadata_type : 1247 relocInfo::oop_type; 1248 // update relocInfo to metadata 1249 nmethod* nm = CodeCache::find_nmethod(instr_pc); 1250 assert(nm != nullptr, "invalid nmethod_pc"); 1251 1252 // The old patch site is now a move instruction so update 1253 // the reloc info so that it will get updated during 1254 // future GCs. 1255 RelocIterator iter(nm, (address)instr_pc, (address)(instr_pc + 1)); 1256 relocInfo::change_reloc_info_for_address(&iter, (address) instr_pc, 1257 relocInfo::none, rtype); 1258 } 1259 1260 } else { 1261 ICache::invalidate_range(copy_buff, *byte_count); 1262 NativeGeneralJump::insert_unconditional(instr_pc, being_initialized_entry); 1263 } 1264 } 1265 } 1266 } 1267 1268 // If we are patching in a non-perm oop, make sure the nmethod 1269 // is on the right list. 1270 { 1271 MutexLocker ml_code (current, CodeCache_lock, Mutex::_no_safepoint_check_flag); 1272 nmethod* nm = CodeCache::find_nmethod(caller_frame.pc()); 1273 guarantee(nm != nullptr, "only nmethods can contain non-perm oops"); 1274 1275 // Since we've patched some oops in the nmethod, 1276 // (re)register it with the heap. 1277 Universe::heap()->register_nmethod(nm); 1278 } 1279 JRT_END 1280 1281 #else // DEOPTIMIZE_WHEN_PATCHING 1282 1283 static bool is_patching_needed(JavaThread* current, Runtime1::StubID stub_id) { 1284 if (stub_id == Runtime1::load_klass_patching_id || 1285 stub_id == Runtime1::load_mirror_patching_id) { 1286 // last java frame on stack 1287 vframeStream vfst(current, true); 1288 assert(!vfst.at_end(), "Java frame must exist"); 1289 1290 methodHandle caller_method(current, vfst.method()); 1291 int bci = vfst.bci(); 1292 Bytecodes::Code code = caller_method()->java_code_at(bci); 1293 1294 switch (code) { 1295 case Bytecodes::_new: 1296 case Bytecodes::_anewarray: 1297 case Bytecodes::_multianewarray: 1298 case Bytecodes::_instanceof: 1299 case Bytecodes::_checkcast: { 1300 Bytecode bc(caller_method(), caller_method->bcp_from(bci)); 1301 constantTag tag = caller_method->constants()->tag_at(bc.get_index_u2(code)); 1302 if (tag.is_unresolved_klass_in_error()) { 1303 return false; // throws resolution error 1304 } 1305 break; 1306 } 1307 1308 default: break; 1309 } 1310 } 1311 return true; 1312 } 1313 1314 void Runtime1::patch_code(JavaThread* current, Runtime1::StubID stub_id) { 1315 #ifndef PRODUCT 1316 if (PrintC1Statistics) { 1317 _patch_code_slowcase_cnt++; 1318 } 1319 #endif 1320 1321 // Enable WXWrite: the function is called by c1 stub as a runtime function 1322 // (see another implementation above). 1323 MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, current)); 1324 1325 if (TracePatching) { 1326 tty->print_cr("Deoptimizing because patch is needed"); 1327 } 1328 1329 RegisterMap reg_map(current, 1330 RegisterMap::UpdateMap::skip, 1331 RegisterMap::ProcessFrames::include, 1332 RegisterMap::WalkContinuation::skip); 1333 1334 frame runtime_frame = current->last_frame(); 1335 frame caller_frame = runtime_frame.sender(®_map); 1336 assert(caller_frame.is_compiled_frame(), "Wrong frame type"); 1337 1338 if (is_patching_needed(current, stub_id)) { 1339 // Make sure the nmethod is invalidated, i.e. made not entrant. 1340 nmethod* nm = CodeCache::find_nmethod(caller_frame.pc()); 1341 if (nm != nullptr) { 1342 nm->make_not_entrant(); 1343 } 1344 } 1345 1346 Deoptimization::deoptimize_frame(current, caller_frame.id()); 1347 // Return to the now deoptimized frame. 1348 postcond(caller_is_deopted(current)); 1349 } 1350 1351 #endif // DEOPTIMIZE_WHEN_PATCHING 1352 1353 // Entry point for compiled code. We want to patch a nmethod. 1354 // We don't do a normal VM transition here because we want to 1355 // know after the patching is complete and any safepoint(s) are taken 1356 // if the calling nmethod was deoptimized. We do this by calling a 1357 // helper method which does the normal VM transition and when it 1358 // completes we can check for deoptimization. This simplifies the 1359 // assembly code in the cpu directories. 1360 // 1361 int Runtime1::move_klass_patching(JavaThread* current) { 1362 // 1363 // NOTE: we are still in Java 1364 // 1365 debug_only(NoHandleMark nhm;) 1366 { 1367 // Enter VM mode 1368 ResetNoHandleMark rnhm; 1369 patch_code(current, load_klass_patching_id); 1370 } 1371 // Back in JAVA, use no oops DON'T safepoint 1372 1373 // Return true if calling code is deoptimized 1374 1375 return caller_is_deopted(current); 1376 } 1377 1378 int Runtime1::move_mirror_patching(JavaThread* current) { 1379 // 1380 // NOTE: we are still in Java 1381 // 1382 debug_only(NoHandleMark nhm;) 1383 { 1384 // Enter VM mode 1385 ResetNoHandleMark rnhm; 1386 patch_code(current, load_mirror_patching_id); 1387 } 1388 // Back in JAVA, use no oops DON'T safepoint 1389 1390 // Return true if calling code is deoptimized 1391 1392 return caller_is_deopted(current); 1393 } 1394 1395 int Runtime1::move_appendix_patching(JavaThread* current) { 1396 // 1397 // NOTE: we are still in Java 1398 // 1399 debug_only(NoHandleMark nhm;) 1400 { 1401 // Enter VM mode 1402 ResetNoHandleMark rnhm; 1403 patch_code(current, load_appendix_patching_id); 1404 } 1405 // Back in JAVA, use no oops DON'T safepoint 1406 1407 // Return true if calling code is deoptimized 1408 1409 return caller_is_deopted(current); 1410 } 1411 1412 // Entry point for compiled code. We want to patch a nmethod. 1413 // We don't do a normal VM transition here because we want to 1414 // know after the patching is complete and any safepoint(s) are taken 1415 // if the calling nmethod was deoptimized. We do this by calling a 1416 // helper method which does the normal VM transition and when it 1417 // completes we can check for deoptimization. This simplifies the 1418 // assembly code in the cpu directories. 1419 // 1420 int Runtime1::access_field_patching(JavaThread* current) { 1421 // 1422 // NOTE: we are still in Java 1423 // 1424 // Handles created in this function will be deleted by the 1425 // HandleMarkCleaner in the transition to the VM. 1426 NoHandleMark nhm; 1427 { 1428 // Enter VM mode 1429 ResetNoHandleMark rnhm; 1430 patch_code(current, access_field_patching_id); 1431 } 1432 // Back in JAVA, use no oops DON'T safepoint 1433 1434 // Return true if calling code is deoptimized 1435 1436 return caller_is_deopted(current); 1437 } 1438 1439 1440 JRT_LEAF(void, Runtime1::trace_block_entry(jint block_id)) 1441 // for now we just print out the block id 1442 tty->print("%d ", block_id); 1443 JRT_END 1444 1445 1446 JRT_LEAF(int, Runtime1::is_instance_of(oopDesc* mirror, oopDesc* obj)) 1447 // had to return int instead of bool, otherwise there may be a mismatch 1448 // between the C calling convention and the Java one. 1449 // e.g., on x86, GCC may clear only %al when returning a bool false, but 1450 // JVM takes the whole %eax as the return value, which may misinterpret 1451 // the return value as a boolean true. 1452 1453 assert(mirror != nullptr, "should null-check on mirror before calling"); 1454 Klass* k = java_lang_Class::as_Klass(mirror); 1455 return (k != nullptr && obj != nullptr && obj->is_a(k)) ? 1 : 0; 1456 JRT_END 1457 1458 JRT_ENTRY(void, Runtime1::predicate_failed_trap(JavaThread* current)) 1459 ResourceMark rm; 1460 1461 RegisterMap reg_map(current, 1462 RegisterMap::UpdateMap::skip, 1463 RegisterMap::ProcessFrames::include, 1464 RegisterMap::WalkContinuation::skip); 1465 frame runtime_frame = current->last_frame(); 1466 frame caller_frame = runtime_frame.sender(®_map); 1467 1468 nmethod* nm = CodeCache::find_nmethod(caller_frame.pc()); 1469 assert (nm != nullptr, "no more nmethod?"); 1470 nm->make_not_entrant(); 1471 1472 methodHandle m(current, nm->method()); 1473 MethodData* mdo = m->method_data(); 1474 1475 if (mdo == nullptr && !HAS_PENDING_EXCEPTION) { 1476 // Build an MDO. Ignore errors like OutOfMemory; 1477 // that simply means we won't have an MDO to update. 1478 Method::build_profiling_method_data(m, THREAD); 1479 if (HAS_PENDING_EXCEPTION) { 1480 // Only metaspace OOM is expected. No Java code executed. 1481 assert((PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())), "we expect only an OOM error here"); 1482 CLEAR_PENDING_EXCEPTION; 1483 } 1484 mdo = m->method_data(); 1485 } 1486 1487 if (mdo != nullptr) { 1488 mdo->inc_trap_count(Deoptimization::Reason_none); 1489 } 1490 1491 if (TracePredicateFailedTraps) { 1492 stringStream ss1, ss2; 1493 vframeStream vfst(current); 1494 Method* inlinee = vfst.method(); 1495 inlinee->print_short_name(&ss1); 1496 m->print_short_name(&ss2); 1497 tty->print_cr("Predicate failed trap in method %s at bci %d inlined in %s at pc " INTPTR_FORMAT, ss1.freeze(), vfst.bci(), ss2.freeze(), p2i(caller_frame.pc())); 1498 } 1499 1500 1501 Deoptimization::deoptimize_frame(current, caller_frame.id()); 1502 1503 JRT_END 1504 1505 // Check exception if AbortVMOnException flag set 1506 JRT_LEAF(void, Runtime1::check_abort_on_vm_exception(oopDesc* ex)) 1507 ResourceMark rm; 1508 const char* message = nullptr; 1509 if (ex->is_a(vmClasses::Throwable_klass())) { 1510 oop msg = java_lang_Throwable::message(ex); 1511 if (msg != nullptr) { 1512 message = java_lang_String::as_utf8_string(msg); 1513 } 1514 } 1515 Exceptions::debug_check_abort(ex->klass()->external_name(), message); 1516 JRT_END 1517 1518 #ifndef PRODUCT 1519 void Runtime1::print_statistics() { 1520 tty->print_cr("C1 Runtime statistics:"); 1521 tty->print_cr(" _resolve_invoke_virtual_cnt: %u", SharedRuntime::_resolve_virtual_ctr); 1522 tty->print_cr(" _resolve_invoke_opt_virtual_cnt: %u", SharedRuntime::_resolve_opt_virtual_ctr); 1523 tty->print_cr(" _resolve_invoke_static_cnt: %u", SharedRuntime::_resolve_static_ctr); 1524 tty->print_cr(" _handle_wrong_method_cnt: %u", SharedRuntime::_wrong_method_ctr); 1525 tty->print_cr(" _ic_miss_cnt: %u", SharedRuntime::_ic_miss_ctr); 1526 tty->print_cr(" _generic_arraycopystub_cnt: %u", _generic_arraycopystub_cnt); 1527 tty->print_cr(" _byte_arraycopy_cnt: %u", _byte_arraycopy_stub_cnt); 1528 tty->print_cr(" _short_arraycopy_cnt: %u", _short_arraycopy_stub_cnt); 1529 tty->print_cr(" _int_arraycopy_cnt: %u", _int_arraycopy_stub_cnt); 1530 tty->print_cr(" _long_arraycopy_cnt: %u", _long_arraycopy_stub_cnt); 1531 tty->print_cr(" _oop_arraycopy_cnt: %u", _oop_arraycopy_stub_cnt); 1532 tty->print_cr(" _arraycopy_slowcase_cnt: %u", _arraycopy_slowcase_cnt); 1533 tty->print_cr(" _arraycopy_checkcast_cnt: %u", _arraycopy_checkcast_cnt); 1534 tty->print_cr(" _arraycopy_checkcast_attempt_cnt:%u", _arraycopy_checkcast_attempt_cnt); 1535 1536 tty->print_cr(" _new_type_array_slowcase_cnt: %u", _new_type_array_slowcase_cnt); 1537 tty->print_cr(" _new_object_array_slowcase_cnt: %u", _new_object_array_slowcase_cnt); 1538 tty->print_cr(" _new_instance_slowcase_cnt: %u", _new_instance_slowcase_cnt); 1539 tty->print_cr(" _new_multi_array_slowcase_cnt: %u", _new_multi_array_slowcase_cnt); 1540 tty->print_cr(" _monitorenter_slowcase_cnt: %u", _monitorenter_slowcase_cnt); 1541 tty->print_cr(" _monitorexit_slowcase_cnt: %u", _monitorexit_slowcase_cnt); 1542 tty->print_cr(" _patch_code_slowcase_cnt: %u", _patch_code_slowcase_cnt); 1543 1544 tty->print_cr(" _throw_range_check_exception_count: %u:", _throw_range_check_exception_count); 1545 tty->print_cr(" _throw_index_exception_count: %u:", _throw_index_exception_count); 1546 tty->print_cr(" _throw_div0_exception_count: %u:", _throw_div0_exception_count); 1547 tty->print_cr(" _throw_null_pointer_exception_count: %u:", _throw_null_pointer_exception_count); 1548 tty->print_cr(" _throw_class_cast_exception_count: %u:", _throw_class_cast_exception_count); 1549 tty->print_cr(" _throw_incompatible_class_change_error_count: %u:", _throw_incompatible_class_change_error_count); 1550 tty->print_cr(" _throw_count: %u:", _throw_count); 1551 1552 SharedRuntime::print_ic_miss_histogram(); 1553 tty->cr(); 1554 } 1555 #endif // PRODUCT