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