1 /* 2 * Copyright (c) 1999, 2024, 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_LIRAssembler.hpp" 30 #include "c1/c1_MacroAssembler.hpp" 31 #include "c1/c1_Runtime1.hpp" 32 #include "classfile/javaClasses.inline.hpp" 33 #include "classfile/vmClasses.hpp" 34 #include "classfile/vmSymbols.hpp" 35 #include "code/codeBlob.hpp" 36 #include "code/compiledIC.hpp" 37 #include "code/scopeDesc.hpp" 38 #include "code/vtableStubs.hpp" 39 #include "compiler/compilationPolicy.hpp" 40 #include "compiler/disassembler.hpp" 41 #include "compiler/oopMap.hpp" 42 #include "gc/shared/barrierSet.hpp" 43 #include "gc/shared/c1/barrierSetC1.hpp" 44 #include "gc/shared/collectedHeap.hpp" 45 #include "interpreter/bytecode.hpp" 46 #include "interpreter/interpreter.hpp" 47 #include "jfr/support/jfrIntrinsics.hpp" 48 #include "logging/log.hpp" 49 #include "memory/oopFactory.hpp" 50 #include "memory/resourceArea.hpp" 51 #include "memory/universe.hpp" 52 #include "oops/access.inline.hpp" 53 #include "oops/objArrayOop.inline.hpp" 54 #include "oops/objArrayKlass.hpp" 55 #include "oops/oop.inline.hpp" 56 #include "prims/jvmtiExport.hpp" 57 #include "runtime/atomic.hpp" 58 #include "runtime/fieldDescriptor.inline.hpp" 59 #include "runtime/frame.inline.hpp" 60 #include "runtime/handles.inline.hpp" 61 #include "runtime/interfaceSupport.inline.hpp" 62 #include "runtime/javaCalls.hpp" 63 #include "runtime/sharedRuntime.hpp" 64 #include "runtime/stackWatermarkSet.hpp" 65 #include "runtime/stubRoutines.hpp" 66 #include "runtime/vframe.inline.hpp" 67 #include "runtime/vframeArray.hpp" 68 #include "runtime/vm_version.hpp" 69 #include "utilities/copy.hpp" 70 #include "utilities/events.hpp" 71 72 73 // Implementation of StubAssembler 74 75 StubAssembler::StubAssembler(CodeBuffer* code, const char * name, int stub_id) : C1_MacroAssembler(code) { 76 _name = name; 77 _must_gc_arguments = false; 78 _frame_size = no_frame_size; 79 _num_rt_args = 0; 80 _stub_id = stub_id; 81 } 82 83 84 void StubAssembler::set_info(const char* name, bool must_gc_arguments) { 85 _name = name; 86 _must_gc_arguments = must_gc_arguments; 87 } 88 89 90 void StubAssembler::set_frame_size(int size) { 91 if (_frame_size == no_frame_size) { 92 _frame_size = size; 93 } 94 assert(_frame_size == size, "can't change the frame size"); 95 } 96 97 98 void StubAssembler::set_num_rt_args(int args) { 99 if (_num_rt_args == 0) { 100 _num_rt_args = args; 101 } 102 assert(_num_rt_args == args, "can't change the number of args"); 103 } 104 105 // Implementation of Runtime1 106 107 CodeBlob* Runtime1::_blobs[(int)C1StubId::NUM_STUBIDS]; 108 109 #define C1_BLOB_NAME_DEFINE(name) "C1 Runtime " # name "_blob", 110 const char *Runtime1::_blob_names[] = { 111 C1_STUBS_DO(C1_BLOB_NAME_DEFINE) 112 }; 113 #undef C1_STUB_NAME_DEFINE 114 115 #ifndef PRODUCT 116 // statistics 117 uint Runtime1::_generic_arraycopystub_cnt = 0; 118 uint Runtime1::_arraycopy_slowcase_cnt = 0; 119 uint Runtime1::_arraycopy_checkcast_cnt = 0; 120 uint Runtime1::_arraycopy_checkcast_attempt_cnt = 0; 121 uint Runtime1::_new_type_array_slowcase_cnt = 0; 122 uint Runtime1::_new_object_array_slowcase_cnt = 0; 123 uint Runtime1::_new_instance_slowcase_cnt = 0; 124 uint Runtime1::_new_multi_array_slowcase_cnt = 0; 125 uint Runtime1::_monitorenter_slowcase_cnt = 0; 126 uint Runtime1::_monitorexit_slowcase_cnt = 0; 127 uint Runtime1::_patch_code_slowcase_cnt = 0; 128 uint Runtime1::_throw_range_check_exception_count = 0; 129 uint Runtime1::_throw_index_exception_count = 0; 130 uint Runtime1::_throw_div0_exception_count = 0; 131 uint Runtime1::_throw_null_pointer_exception_count = 0; 132 uint Runtime1::_throw_class_cast_exception_count = 0; 133 uint Runtime1::_throw_incompatible_class_change_error_count = 0; 134 uint Runtime1::_throw_count = 0; 135 136 static uint _byte_arraycopy_stub_cnt = 0; 137 static uint _short_arraycopy_stub_cnt = 0; 138 static uint _int_arraycopy_stub_cnt = 0; 139 static uint _long_arraycopy_stub_cnt = 0; 140 static uint _oop_arraycopy_stub_cnt = 0; 141 142 address Runtime1::arraycopy_count_address(BasicType type) { 143 switch (type) { 144 case T_BOOLEAN: 145 case T_BYTE: return (address)&_byte_arraycopy_stub_cnt; 146 case T_CHAR: 147 case T_SHORT: return (address)&_short_arraycopy_stub_cnt; 148 case T_FLOAT: 149 case T_INT: return (address)&_int_arraycopy_stub_cnt; 150 case T_DOUBLE: 151 case T_LONG: return (address)&_long_arraycopy_stub_cnt; 152 case T_ARRAY: 153 case T_OBJECT: return (address)&_oop_arraycopy_stub_cnt; 154 default: 155 ShouldNotReachHere(); 156 return nullptr; 157 } 158 } 159 160 161 #endif 162 163 // Simple helper to see if the caller of a runtime stub which 164 // entered the VM has been deoptimized 165 166 static bool caller_is_deopted(JavaThread* current) { 167 RegisterMap reg_map(current, 168 RegisterMap::UpdateMap::skip, 169 RegisterMap::ProcessFrames::include, 170 RegisterMap::WalkContinuation::skip); 171 frame runtime_frame = current->last_frame(); 172 frame caller_frame = runtime_frame.sender(®_map); 173 assert(caller_frame.is_compiled_frame(), "must be compiled"); 174 return caller_frame.is_deoptimized_frame(); 175 } 176 177 // Stress deoptimization 178 static void deopt_caller(JavaThread* current) { 179 if (!caller_is_deopted(current)) { 180 RegisterMap reg_map(current, 181 RegisterMap::UpdateMap::skip, 182 RegisterMap::ProcessFrames::include, 183 RegisterMap::WalkContinuation::skip); 184 frame runtime_frame = current->last_frame(); 185 frame caller_frame = runtime_frame.sender(®_map); 186 Deoptimization::deoptimize_frame(current, caller_frame.id()); 187 assert(caller_is_deopted(current), "Must be deoptimized"); 188 } 189 } 190 191 class C1StubIdStubAssemblerCodeGenClosure: public StubAssemblerCodeGenClosure { 192 private: 193 C1StubId _id; 194 public: 195 C1StubIdStubAssemblerCodeGenClosure(C1StubId id) : _id(id) {} 196 virtual OopMapSet* generate_code(StubAssembler* sasm) { 197 return Runtime1::generate_code_for(_id, sasm); 198 } 199 }; 200 201 CodeBlob* Runtime1::generate_blob(BufferBlob* buffer_blob, C1StubId id, const char* name, bool expect_oop_map, StubAssemblerCodeGenClosure* cl) { 202 ResourceMark rm; 203 // create code buffer for code storage 204 CodeBuffer code(buffer_blob); 205 206 OopMapSet* oop_maps; 207 int frame_size; 208 bool must_gc_arguments; 209 210 Compilation::setup_code_buffer(&code, 0); 211 212 // create assembler for code generation 213 StubAssembler* sasm = new StubAssembler(&code, name, (int)id); 214 // generate code for runtime stub 215 oop_maps = cl->generate_code(sasm); 216 assert(oop_maps == nullptr || sasm->frame_size() != no_frame_size, 217 "if stub has an oop map it must have a valid frame size"); 218 assert(!expect_oop_map || oop_maps != nullptr, "must have an oopmap"); 219 220 // align so printing shows nop's instead of random code at the end (SimpleStubs are aligned) 221 sasm->align(BytesPerWord); 222 // make sure all code is in code buffer 223 sasm->flush(); 224 225 frame_size = sasm->frame_size(); 226 must_gc_arguments = sasm->must_gc_arguments(); 227 // create blob - distinguish a few special cases 228 CodeBlob* blob = RuntimeStub::new_runtime_stub(name, 229 &code, 230 CodeOffsets::frame_never_safe, 231 frame_size, 232 oop_maps, 233 must_gc_arguments); 234 assert(blob != nullptr, "blob must exist"); 235 return blob; 236 } 237 238 void Runtime1::generate_blob_for(BufferBlob* buffer_blob, C1StubId id) { 239 assert(C1StubId::NO_STUBID < id && id < C1StubId::NUM_STUBIDS, "illegal stub id"); 240 bool expect_oop_map = true; 241 #ifdef ASSERT 242 // Make sure that stubs that need oopmaps have them 243 switch (id) { 244 // These stubs don't need to have an oopmap 245 case C1StubId::dtrace_object_alloc_id: 246 case C1StubId::slow_subtype_check_id: 247 case C1StubId::fpu2long_stub_id: 248 case C1StubId::unwind_exception_id: 249 case C1StubId::counter_overflow_id: 250 expect_oop_map = false; 251 break; 252 default: 253 break; 254 } 255 #endif 256 C1StubIdStubAssemblerCodeGenClosure cl(id); 257 CodeBlob* blob = generate_blob(buffer_blob, id, name_for(id), expect_oop_map, &cl); 258 // install blob 259 _blobs[(int)id] = blob; 260 } 261 262 void Runtime1::initialize(BufferBlob* blob) { 263 // platform-dependent initialization 264 initialize_pd(); 265 // generate stubs 266 int limit = (int)C1StubId::NUM_STUBIDS; 267 for (int id = 0; id < limit; id++) generate_blob_for(blob, (C1StubId)id); 268 // printing 269 #ifndef PRODUCT 270 if (PrintSimpleStubs) { 271 ResourceMark rm; 272 for (int id = 0; id < limit; id++) { 273 _blobs[id]->print(); 274 if (_blobs[id]->oop_maps() != nullptr) { 275 _blobs[id]->oop_maps()->print(); 276 } 277 } 278 } 279 #endif 280 BarrierSetC1* bs = BarrierSet::barrier_set()->barrier_set_c1(); 281 bs->generate_c1_runtime_stubs(blob); 282 } 283 284 CodeBlob* Runtime1::blob_for(C1StubId id) { 285 assert(C1StubId::NO_STUBID < id && id < C1StubId::NUM_STUBIDS, "illegal stub id"); 286 return _blobs[(int)id]; 287 } 288 289 290 const char* Runtime1::name_for(C1StubId id) { 291 assert(C1StubId::NO_STUBID < id && id < C1StubId::NUM_STUBIDS, "illegal stub id"); 292 return _blob_names[(int)id]; 293 } 294 295 const char* Runtime1::name_for_address(address entry) { 296 int limit = (int)C1StubId::NUM_STUBIDS; 297 for (int i = 0; i < limit; i++) { 298 C1StubId id = (C1StubId)i; 299 if (entry == entry_for(id)) return name_for(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::dtanh()); 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, C1StubId id)) 431 tty->print_cr("Runtime1::entry_for(%d) returned unimplemented entry point", (int)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 = nullptr; 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!= nullptr && 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 != nullptr) { 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 nullptr; 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(C1StubId::handle_exception_from_callee_id)) { 531 // The C1StubId::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 != nullptr, "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; // print_value_string 559 stringStream tempst; 560 assert(nm->method() != nullptr, "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.freeze()); 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 != nullptr) { 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 as null). 612 address continuation = nullptr; 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 != nullptr && !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 = nullptr; 665 address continuation = nullptr; 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 != nullptr && caller_is_deopted(current)) { 676 continuation = SharedRuntime::deopt_blob()->unpack_with_exception_in_tls(); 677 } 678 679 assert(continuation != nullptr, "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 os::snprintf_checked(message, sizeof(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 os::snprintf_checked(message, sizeof(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 (LockingMode == LM_MONITOR) { 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 assert(current == JavaThread::current(), "pre-condition"); 769 #ifndef PRODUCT 770 if (PrintC1Statistics) { 771 _monitorexit_slowcase_cnt++; 772 } 773 #endif 774 assert(current->last_Java_sp(), "last_Java_sp must be set"); 775 oop obj = lock->obj(); 776 assert(oopDesc::is_oop(obj), "must be null or an object"); 777 SharedRuntime::monitor_exit_helper(obj, lock->lock(), current); 778 JRT_END 779 780 // Cf. OptoRuntime::deoptimize_caller_frame 781 JRT_ENTRY(void, Runtime1::deoptimize(JavaThread* current, jint trap_request)) 782 // Called from within the owner thread, so no need for safepoint 783 RegisterMap reg_map(current, 784 RegisterMap::UpdateMap::skip, 785 RegisterMap::ProcessFrames::include, 786 RegisterMap::WalkContinuation::skip); 787 frame stub_frame = current->last_frame(); 788 assert(stub_frame.is_runtime_frame(), "Sanity check"); 789 frame caller_frame = stub_frame.sender(®_map); 790 nmethod* nm = caller_frame.cb()->as_nmethod_or_null(); 791 assert(nm != nullptr, "Sanity check"); 792 methodHandle method(current, nm->method()); 793 assert(nm == CodeCache::find_nmethod(caller_frame.pc()), "Should be the same"); 794 Deoptimization::DeoptAction action = Deoptimization::trap_request_action(trap_request); 795 Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(trap_request); 796 797 if (action == Deoptimization::Action_make_not_entrant) { 798 if (nm->make_not_entrant()) { 799 if (reason == Deoptimization::Reason_tenured) { 800 MethodData* trap_mdo = Deoptimization::get_method_data(current, method, true /*create_if_missing*/); 801 if (trap_mdo != nullptr) { 802 trap_mdo->inc_tenure_traps(); 803 } 804 } 805 } 806 } 807 808 // Deoptimize the caller frame. 809 Deoptimization::deoptimize_frame(current, caller_frame.id()); 810 // Return to the now deoptimized frame. 811 JRT_END 812 813 814 #ifndef DEOPTIMIZE_WHEN_PATCHING 815 816 static Klass* resolve_field_return_klass(const methodHandle& caller, int bci, TRAPS) { 817 Bytecode_field field_access(caller, bci); 818 // This can be static or non-static field access 819 Bytecodes::Code code = field_access.code(); 820 821 // We must load class, initialize class and resolve the field 822 fieldDescriptor result; // initialize class if needed 823 constantPoolHandle constants(THREAD, caller->constants()); 824 LinkResolver::resolve_field_access(result, constants, field_access.index(), caller, Bytecodes::java_code(code), CHECK_NULL); 825 return result.field_holder(); 826 } 827 828 829 // 830 // This routine patches sites where a class wasn't loaded or 831 // initialized at the time the code was generated. It handles 832 // references to classes, fields and forcing of initialization. Most 833 // of the cases are straightforward and involving simply forcing 834 // resolution of a class, rewriting the instruction stream with the 835 // needed constant and replacing the call in this function with the 836 // patched code. The case for static field is more complicated since 837 // the thread which is in the process of initializing a class can 838 // access it's static fields but other threads can't so the code 839 // either has to deoptimize when this case is detected or execute a 840 // check that the current thread is the initializing thread. The 841 // current 842 // 843 // Patches basically look like this: 844 // 845 // 846 // patch_site: jmp patch stub ;; will be patched 847 // continue: ... 848 // ... 849 // ... 850 // ... 851 // 852 // They have a stub which looks like this: 853 // 854 // ;; patch body 855 // movl <const>, reg (for class constants) 856 // <or> movl [reg1 + <const>], reg (for field offsets) 857 // <or> movl reg, [reg1 + <const>] (for field offsets) 858 // <being_init offset> <bytes to copy> <bytes to skip> 859 // patch_stub: call Runtime1::patch_code (through a runtime stub) 860 // jmp patch_site 861 // 862 // 863 // A normal patch is done by rewriting the patch body, usually a move, 864 // and then copying it into place over top of the jmp instruction 865 // being careful to flush caches and doing it in an MP-safe way. The 866 // constants following the patch body are used to find various pieces 867 // of the patch relative to the call site for Runtime1::patch_code. 868 // The case for getstatic and putstatic is more complicated because 869 // getstatic and putstatic have special semantics when executing while 870 // the class is being initialized. getstatic/putstatic on a class 871 // which is being_initialized may be executed by the initializing 872 // thread but other threads have to block when they execute it. This 873 // is accomplished in compiled code by executing a test of the current 874 // thread against the initializing thread of the class. It's emitted 875 // as boilerplate in their stub which allows the patched code to be 876 // executed before it's copied back into the main body of the nmethod. 877 // 878 // being_init: get_thread(<tmp reg> 879 // cmpl [reg1 + <init_thread_offset>], <tmp reg> 880 // jne patch_stub 881 // movl [reg1 + <const>], reg (for field offsets) <or> 882 // movl reg, [reg1 + <const>] (for field offsets) 883 // jmp continue 884 // <being_init offset> <bytes to copy> <bytes to skip> 885 // patch_stub: jmp Runtime1::patch_code (through a runtime stub) 886 // jmp patch_site 887 // 888 // If the class is being initialized the patch body is rewritten and 889 // the patch site is rewritten to jump to being_init, instead of 890 // patch_stub. Whenever this code is executed it checks the current 891 // thread against the initializing thread so other threads will enter 892 // the runtime and end up blocked waiting the class to finish 893 // initializing inside the calls to resolve_field below. The 894 // initializing class will continue on it's way. Once the class is 895 // fully_initialized, the intializing_thread of the class becomes 896 // null, so the next thread to execute this code will fail the test, 897 // call into patch_code and complete the patching process by copying 898 // the patch body back into the main part of the nmethod and resume 899 // executing. 900 901 // NB: 902 // 903 // Patchable instruction sequences inherently exhibit race conditions, 904 // where thread A is patching an instruction at the same time thread B 905 // is executing it. The algorithms we use ensure that any observation 906 // that B can make on any intermediate states during A's patching will 907 // always end up with a correct outcome. This is easiest if there are 908 // few or no intermediate states. (Some inline caches have two 909 // related instructions that must be patched in tandem. For those, 910 // intermediate states seem to be unavoidable, but we will get the 911 // right answer from all possible observation orders.) 912 // 913 // When patching the entry instruction at the head of a method, or a 914 // linkable call instruction inside of a method, we try very hard to 915 // use a patch sequence which executes as a single memory transaction. 916 // This means, in practice, that when thread A patches an instruction, 917 // it should patch a 32-bit or 64-bit word that somehow overlaps the 918 // instruction or is contained in it. We believe that memory hardware 919 // will never break up such a word write, if it is naturally aligned 920 // for the word being written. We also know that some CPUs work very 921 // hard to create atomic updates even of naturally unaligned words, 922 // but we don't want to bet the farm on this always working. 923 // 924 // Therefore, if there is any chance of a race condition, we try to 925 // patch only naturally aligned words, as single, full-word writes. 926 927 JRT_ENTRY(void, Runtime1::patch_code(JavaThread* current, C1StubId stub_id )) 928 #ifndef PRODUCT 929 if (PrintC1Statistics) { 930 _patch_code_slowcase_cnt++; 931 } 932 #endif 933 934 ResourceMark rm(current); 935 RegisterMap reg_map(current, 936 RegisterMap::UpdateMap::skip, 937 RegisterMap::ProcessFrames::include, 938 RegisterMap::WalkContinuation::skip); 939 frame runtime_frame = current->last_frame(); 940 frame caller_frame = runtime_frame.sender(®_map); 941 942 // last java frame on stack 943 vframeStream vfst(current, true); 944 assert(!vfst.at_end(), "Java frame must exist"); 945 946 methodHandle caller_method(current, vfst.method()); 947 // Note that caller_method->code() may not be same as caller_code because of OSR's 948 // Note also that in the presence of inlining it is not guaranteed 949 // that caller_method() == caller_code->method() 950 951 int bci = vfst.bci(); 952 Bytecodes::Code code = caller_method()->java_code_at(bci); 953 954 // this is used by assertions in the access_field_patching_id 955 BasicType patch_field_type = T_ILLEGAL; 956 bool deoptimize_for_volatile = false; 957 bool deoptimize_for_atomic = false; 958 int patch_field_offset = -1; 959 Klass* init_klass = nullptr; // klass needed by load_klass_patching code 960 Klass* load_klass = nullptr; // klass needed by load_klass_patching code 961 Handle mirror(current, nullptr); // oop needed by load_mirror_patching code 962 Handle appendix(current, nullptr); // oop needed by appendix_patching code 963 bool load_klass_or_mirror_patch_id = 964 (stub_id == C1StubId::load_klass_patching_id || stub_id == C1StubId::load_mirror_patching_id); 965 966 if (stub_id == C1StubId::access_field_patching_id) { 967 968 Bytecode_field field_access(caller_method, bci); 969 fieldDescriptor result; // initialize class if needed 970 Bytecodes::Code code = field_access.code(); 971 constantPoolHandle constants(current, caller_method->constants()); 972 LinkResolver::resolve_field_access(result, constants, field_access.index(), caller_method, Bytecodes::java_code(code), CHECK); 973 patch_field_offset = result.offset(); 974 975 // If we're patching a field which is volatile then at compile it 976 // must not have been know to be volatile, so the generated code 977 // isn't correct for a volatile reference. The nmethod has to be 978 // deoptimized so that the code can be regenerated correctly. 979 // This check is only needed for access_field_patching since this 980 // is the path for patching field offsets. load_klass is only 981 // used for patching references to oops which don't need special 982 // handling in the volatile case. 983 984 deoptimize_for_volatile = result.access_flags().is_volatile(); 985 986 // If we are patching a field which should be atomic, then 987 // the generated code is not correct either, force deoptimizing. 988 // We need to only cover T_LONG and T_DOUBLE fields, as we can 989 // break access atomicity only for them. 990 991 // Strictly speaking, the deoptimization on 64-bit platforms 992 // is unnecessary, and T_LONG stores on 32-bit platforms need 993 // to be handled by special patching code when AlwaysAtomicAccesses 994 // becomes product feature. At this point, we are still going 995 // for the deoptimization for consistency against volatile 996 // accesses. 997 998 patch_field_type = result.field_type(); 999 deoptimize_for_atomic = (AlwaysAtomicAccesses && (patch_field_type == T_DOUBLE || patch_field_type == T_LONG)); 1000 1001 } else if (load_klass_or_mirror_patch_id) { 1002 Klass* k = nullptr; 1003 switch (code) { 1004 case Bytecodes::_putstatic: 1005 case Bytecodes::_getstatic: 1006 { Klass* klass = resolve_field_return_klass(caller_method, bci, CHECK); 1007 init_klass = klass; 1008 mirror = Handle(current, klass->java_mirror()); 1009 } 1010 break; 1011 case Bytecodes::_new: 1012 { Bytecode_new bnew(caller_method(), caller_method->bcp_from(bci)); 1013 k = caller_method->constants()->klass_at(bnew.index(), CHECK); 1014 } 1015 break; 1016 case Bytecodes::_multianewarray: 1017 { Bytecode_multianewarray mna(caller_method(), caller_method->bcp_from(bci)); 1018 k = caller_method->constants()->klass_at(mna.index(), CHECK); 1019 } 1020 break; 1021 case Bytecodes::_instanceof: 1022 { Bytecode_instanceof io(caller_method(), caller_method->bcp_from(bci)); 1023 k = caller_method->constants()->klass_at(io.index(), CHECK); 1024 } 1025 break; 1026 case Bytecodes::_checkcast: 1027 { Bytecode_checkcast cc(caller_method(), caller_method->bcp_from(bci)); 1028 k = caller_method->constants()->klass_at(cc.index(), CHECK); 1029 } 1030 break; 1031 case Bytecodes::_anewarray: 1032 { Bytecode_anewarray anew(caller_method(), caller_method->bcp_from(bci)); 1033 Klass* ek = caller_method->constants()->klass_at(anew.index(), CHECK); 1034 k = ek->array_klass(CHECK); 1035 } 1036 break; 1037 case Bytecodes::_ldc: 1038 case Bytecodes::_ldc_w: 1039 case Bytecodes::_ldc2_w: 1040 { 1041 Bytecode_loadconstant cc(caller_method, bci); 1042 oop m = cc.resolve_constant(CHECK); 1043 mirror = Handle(current, m); 1044 } 1045 break; 1046 default: fatal("unexpected bytecode for load_klass_or_mirror_patch_id"); 1047 } 1048 load_klass = k; 1049 } else if (stub_id == C1StubId::load_appendix_patching_id) { 1050 Bytecode_invoke bytecode(caller_method, bci); 1051 Bytecodes::Code bc = bytecode.invoke_code(); 1052 1053 CallInfo info; 1054 constantPoolHandle pool(current, caller_method->constants()); 1055 int index = bytecode.index(); 1056 LinkResolver::resolve_invoke(info, Handle(), pool, index, bc, CHECK); 1057 switch (bc) { 1058 case Bytecodes::_invokehandle: { 1059 ResolvedMethodEntry* entry = pool->cache()->set_method_handle(index, info); 1060 appendix = Handle(current, pool->cache()->appendix_if_resolved(entry)); 1061 break; 1062 } 1063 case Bytecodes::_invokedynamic: { 1064 appendix = Handle(current, pool->cache()->set_dynamic_call(info, 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_code (current, CodeCache_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 == C1StubId::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 == C1StubId::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 == C1StubId::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 == C1StubId::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 == C1StubId::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 == C1StubId::load_mirror_patching_id || 1215 stub_id == C1StubId::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 == C1StubId::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 == C1StubId::load_appendix_patching_id) { 1244 relocInfo::relocType rtype = 1245 (stub_id == C1StubId::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 // If we are patching in a non-perm oop, make sure the nmethod 1267 // is on the right list. 1268 nmethod* nm = CodeCache::find_nmethod(caller_frame.pc()); 1269 guarantee(nm != nullptr, "only nmethods can contain non-perm oops"); 1270 1271 // Since we've patched some oops in the nmethod, 1272 // (re)register it with the heap. 1273 Universe::heap()->register_nmethod(nm); 1274 } 1275 JRT_END 1276 1277 #else // DEOPTIMIZE_WHEN_PATCHING 1278 1279 static bool is_patching_needed(JavaThread* current, C1StubId stub_id) { 1280 if (stub_id == C1StubId::load_klass_patching_id || 1281 stub_id == C1StubId::load_mirror_patching_id) { 1282 // last java frame on stack 1283 vframeStream vfst(current, true); 1284 assert(!vfst.at_end(), "Java frame must exist"); 1285 1286 methodHandle caller_method(current, vfst.method()); 1287 int bci = vfst.bci(); 1288 Bytecodes::Code code = caller_method()->java_code_at(bci); 1289 1290 switch (code) { 1291 case Bytecodes::_new: 1292 case Bytecodes::_anewarray: 1293 case Bytecodes::_multianewarray: 1294 case Bytecodes::_instanceof: 1295 case Bytecodes::_checkcast: { 1296 Bytecode bc(caller_method(), caller_method->bcp_from(bci)); 1297 constantTag tag = caller_method->constants()->tag_at(bc.get_index_u2(code)); 1298 if (tag.is_unresolved_klass_in_error()) { 1299 return false; // throws resolution error 1300 } 1301 break; 1302 } 1303 1304 default: break; 1305 } 1306 } 1307 return true; 1308 } 1309 1310 void Runtime1::patch_code(JavaThread* current, C1StubId stub_id) { 1311 #ifndef PRODUCT 1312 if (PrintC1Statistics) { 1313 _patch_code_slowcase_cnt++; 1314 } 1315 #endif 1316 1317 // Enable WXWrite: the function is called by c1 stub as a runtime function 1318 // (see another implementation above). 1319 MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, current)); 1320 1321 if (TracePatching) { 1322 tty->print_cr("Deoptimizing because patch is needed"); 1323 } 1324 1325 RegisterMap reg_map(current, 1326 RegisterMap::UpdateMap::skip, 1327 RegisterMap::ProcessFrames::include, 1328 RegisterMap::WalkContinuation::skip); 1329 1330 frame runtime_frame = current->last_frame(); 1331 frame caller_frame = runtime_frame.sender(®_map); 1332 assert(caller_frame.is_compiled_frame(), "Wrong frame type"); 1333 1334 if (is_patching_needed(current, stub_id)) { 1335 // Make sure the nmethod is invalidated, i.e. made not entrant. 1336 nmethod* nm = CodeCache::find_nmethod(caller_frame.pc()); 1337 if (nm != nullptr) { 1338 nm->make_not_entrant(); 1339 } 1340 } 1341 1342 Deoptimization::deoptimize_frame(current, caller_frame.id()); 1343 // Return to the now deoptimized frame. 1344 postcond(caller_is_deopted(current)); 1345 } 1346 1347 #endif // DEOPTIMIZE_WHEN_PATCHING 1348 1349 // Entry point for compiled code. We want to patch a nmethod. 1350 // We don't do a normal VM transition here because we want to 1351 // know after the patching is complete and any safepoint(s) are taken 1352 // if the calling nmethod was deoptimized. We do this by calling a 1353 // helper method which does the normal VM transition and when it 1354 // completes we can check for deoptimization. This simplifies the 1355 // assembly code in the cpu directories. 1356 // 1357 int Runtime1::move_klass_patching(JavaThread* current) { 1358 // 1359 // NOTE: we are still in Java 1360 // 1361 debug_only(NoHandleMark nhm;) 1362 { 1363 // Enter VM mode 1364 ResetNoHandleMark rnhm; 1365 patch_code(current, C1StubId::load_klass_patching_id); 1366 } 1367 // Back in JAVA, use no oops DON'T safepoint 1368 1369 // Return true if calling code is deoptimized 1370 1371 return caller_is_deopted(current); 1372 } 1373 1374 int Runtime1::move_mirror_patching(JavaThread* current) { 1375 // 1376 // NOTE: we are still in Java 1377 // 1378 debug_only(NoHandleMark nhm;) 1379 { 1380 // Enter VM mode 1381 ResetNoHandleMark rnhm; 1382 patch_code(current, C1StubId::load_mirror_patching_id); 1383 } 1384 // Back in JAVA, use no oops DON'T safepoint 1385 1386 // Return true if calling code is deoptimized 1387 1388 return caller_is_deopted(current); 1389 } 1390 1391 int Runtime1::move_appendix_patching(JavaThread* current) { 1392 // 1393 // NOTE: we are still in Java 1394 // 1395 debug_only(NoHandleMark nhm;) 1396 { 1397 // Enter VM mode 1398 ResetNoHandleMark rnhm; 1399 patch_code(current, C1StubId::load_appendix_patching_id); 1400 } 1401 // Back in JAVA, use no oops DON'T safepoint 1402 1403 // Return true if calling code is deoptimized 1404 1405 return caller_is_deopted(current); 1406 } 1407 1408 // Entry point for compiled code. We want to patch a nmethod. 1409 // We don't do a normal VM transition here because we want to 1410 // know after the patching is complete and any safepoint(s) are taken 1411 // if the calling nmethod was deoptimized. We do this by calling a 1412 // helper method which does the normal VM transition and when it 1413 // completes we can check for deoptimization. This simplifies the 1414 // assembly code in the cpu directories. 1415 // 1416 int Runtime1::access_field_patching(JavaThread* current) { 1417 // 1418 // NOTE: we are still in Java 1419 // 1420 // Handles created in this function will be deleted by the 1421 // HandleMarkCleaner in the transition to the VM. 1422 NoHandleMark nhm; 1423 { 1424 // Enter VM mode 1425 ResetNoHandleMark rnhm; 1426 patch_code(current, C1StubId::access_field_patching_id); 1427 } 1428 // Back in JAVA, use no oops DON'T safepoint 1429 1430 // Return true if calling code is deoptimized 1431 1432 return caller_is_deopted(current); 1433 } 1434 1435 1436 JRT_LEAF(void, Runtime1::trace_block_entry(jint block_id)) 1437 // for now we just print out the block id 1438 tty->print("%d ", block_id); 1439 JRT_END 1440 1441 1442 JRT_LEAF(int, Runtime1::is_instance_of(oopDesc* mirror, oopDesc* obj)) 1443 // had to return int instead of bool, otherwise there may be a mismatch 1444 // between the C calling convention and the Java one. 1445 // e.g., on x86, GCC may clear only %al when returning a bool false, but 1446 // JVM takes the whole %eax as the return value, which may misinterpret 1447 // the return value as a boolean true. 1448 1449 assert(mirror != nullptr, "should null-check on mirror before calling"); 1450 Klass* k = java_lang_Class::as_Klass(mirror); 1451 return (k != nullptr && obj != nullptr && obj->is_a(k)) ? 1 : 0; 1452 JRT_END 1453 1454 JRT_ENTRY(void, Runtime1::predicate_failed_trap(JavaThread* current)) 1455 ResourceMark rm; 1456 1457 RegisterMap reg_map(current, 1458 RegisterMap::UpdateMap::skip, 1459 RegisterMap::ProcessFrames::include, 1460 RegisterMap::WalkContinuation::skip); 1461 frame runtime_frame = current->last_frame(); 1462 frame caller_frame = runtime_frame.sender(®_map); 1463 1464 nmethod* nm = CodeCache::find_nmethod(caller_frame.pc()); 1465 assert (nm != nullptr, "no more nmethod?"); 1466 nm->make_not_entrant(); 1467 1468 methodHandle m(current, nm->method()); 1469 MethodData* mdo = m->method_data(); 1470 1471 if (mdo == nullptr && !HAS_PENDING_EXCEPTION) { 1472 // Build an MDO. Ignore errors like OutOfMemory; 1473 // that simply means we won't have an MDO to update. 1474 Method::build_profiling_method_data(m, THREAD); 1475 if (HAS_PENDING_EXCEPTION) { 1476 // Only metaspace OOM is expected. No Java code executed. 1477 assert((PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())), "we expect only an OOM error here"); 1478 CLEAR_PENDING_EXCEPTION; 1479 } 1480 mdo = m->method_data(); 1481 } 1482 1483 if (mdo != nullptr) { 1484 mdo->inc_trap_count(Deoptimization::Reason_none); 1485 } 1486 1487 if (TracePredicateFailedTraps) { 1488 stringStream ss1, ss2; 1489 vframeStream vfst(current); 1490 Method* inlinee = vfst.method(); 1491 inlinee->print_short_name(&ss1); 1492 m->print_short_name(&ss2); 1493 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())); 1494 } 1495 1496 1497 Deoptimization::deoptimize_frame(current, caller_frame.id()); 1498 1499 JRT_END 1500 1501 // Check exception if AbortVMOnException flag set 1502 JRT_LEAF(void, Runtime1::check_abort_on_vm_exception(oopDesc* ex)) 1503 ResourceMark rm; 1504 const char* message = nullptr; 1505 if (ex->is_a(vmClasses::Throwable_klass())) { 1506 oop msg = java_lang_Throwable::message(ex); 1507 if (msg != nullptr) { 1508 message = java_lang_String::as_utf8_string(msg); 1509 } 1510 } 1511 Exceptions::debug_check_abort(ex->klass()->external_name(), message); 1512 JRT_END 1513 1514 #ifndef PRODUCT 1515 void Runtime1::print_statistics() { 1516 tty->print_cr("C1 Runtime statistics:"); 1517 tty->print_cr(" _resolve_invoke_virtual_cnt: %u", SharedRuntime::_resolve_virtual_ctr); 1518 tty->print_cr(" _resolve_invoke_opt_virtual_cnt: %u", SharedRuntime::_resolve_opt_virtual_ctr); 1519 tty->print_cr(" _resolve_invoke_static_cnt: %u", SharedRuntime::_resolve_static_ctr); 1520 tty->print_cr(" _handle_wrong_method_cnt: %u", SharedRuntime::_wrong_method_ctr); 1521 tty->print_cr(" _ic_miss_cnt: %u", SharedRuntime::_ic_miss_ctr); 1522 tty->print_cr(" _generic_arraycopystub_cnt: %u", _generic_arraycopystub_cnt); 1523 tty->print_cr(" _byte_arraycopy_cnt: %u", _byte_arraycopy_stub_cnt); 1524 tty->print_cr(" _short_arraycopy_cnt: %u", _short_arraycopy_stub_cnt); 1525 tty->print_cr(" _int_arraycopy_cnt: %u", _int_arraycopy_stub_cnt); 1526 tty->print_cr(" _long_arraycopy_cnt: %u", _long_arraycopy_stub_cnt); 1527 tty->print_cr(" _oop_arraycopy_cnt: %u", _oop_arraycopy_stub_cnt); 1528 tty->print_cr(" _arraycopy_slowcase_cnt: %u", _arraycopy_slowcase_cnt); 1529 tty->print_cr(" _arraycopy_checkcast_cnt: %u", _arraycopy_checkcast_cnt); 1530 tty->print_cr(" _arraycopy_checkcast_attempt_cnt:%u", _arraycopy_checkcast_attempt_cnt); 1531 1532 tty->print_cr(" _new_type_array_slowcase_cnt: %u", _new_type_array_slowcase_cnt); 1533 tty->print_cr(" _new_object_array_slowcase_cnt: %u", _new_object_array_slowcase_cnt); 1534 tty->print_cr(" _new_instance_slowcase_cnt: %u", _new_instance_slowcase_cnt); 1535 tty->print_cr(" _new_multi_array_slowcase_cnt: %u", _new_multi_array_slowcase_cnt); 1536 tty->print_cr(" _monitorenter_slowcase_cnt: %u", _monitorenter_slowcase_cnt); 1537 tty->print_cr(" _monitorexit_slowcase_cnt: %u", _monitorexit_slowcase_cnt); 1538 tty->print_cr(" _patch_code_slowcase_cnt: %u", _patch_code_slowcase_cnt); 1539 1540 tty->print_cr(" _throw_range_check_exception_count: %u:", _throw_range_check_exception_count); 1541 tty->print_cr(" _throw_index_exception_count: %u:", _throw_index_exception_count); 1542 tty->print_cr(" _throw_div0_exception_count: %u:", _throw_div0_exception_count); 1543 tty->print_cr(" _throw_null_pointer_exception_count: %u:", _throw_null_pointer_exception_count); 1544 tty->print_cr(" _throw_class_cast_exception_count: %u:", _throw_class_cast_exception_count); 1545 tty->print_cr(" _throw_incompatible_class_change_error_count: %u:", _throw_incompatible_class_change_error_count); 1546 tty->print_cr(" _throw_count: %u:", _throw_count); 1547 1548 SharedRuntime::print_ic_miss_histogram(); 1549 tty->cr(); 1550 } 1551 #endif // PRODUCT