1 /* 2 * Copyright (c) 1997, 2019, 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 "jvm.h" 27 #include "code/codeCache.hpp" 28 #include "code/compiledIC.hpp" 29 #include "code/compiledMethod.inline.hpp" 30 #include "code/dependencies.hpp" 31 #include "code/nativeInst.hpp" 32 #include "code/nmethod.hpp" 33 #include "code/scopeDesc.hpp" 34 #include "compiler/abstractCompiler.hpp" 35 #include "compiler/compileBroker.hpp" 36 #include "compiler/compileLog.hpp" 37 #include "compiler/compilerDirectives.hpp" 38 #include "compiler/directivesParser.hpp" 39 #include "compiler/disassembler.hpp" 40 #include "interpreter/bytecode.hpp" 41 #include "logging/log.hpp" 42 #include "logging/logStream.hpp" 43 #include "memory/allocation.inline.hpp" 44 #include "memory/resourceArea.hpp" 45 #include "oops/access.inline.hpp" 46 #include "oops/method.inline.hpp" 47 #include "oops/methodData.hpp" 48 #include "oops/oop.inline.hpp" 49 #include "prims/jvmtiImpl.hpp" 50 #include "runtime/atomic.hpp" 51 #include "runtime/flags/flagSetting.hpp" 52 #include "runtime/frame.inline.hpp" 53 #include "runtime/handles.inline.hpp" 54 #include "runtime/jniHandles.inline.hpp" 55 #include "runtime/orderAccess.hpp" 56 #include "runtime/os.hpp" 57 #include "runtime/safepointVerifiers.hpp" 58 #include "runtime/sharedRuntime.hpp" 59 #include "runtime/sweeper.hpp" 60 #include "runtime/vmThread.hpp" 61 #include "utilities/align.hpp" 62 #include "utilities/dtrace.hpp" 63 #include "utilities/events.hpp" 64 #include "utilities/resourceHash.hpp" 65 #include "utilities/xmlstream.hpp" 66 #if INCLUDE_JVMCI 67 #include "jvmci/jvmciJavaClasses.hpp" 68 #endif 69 70 #ifdef DTRACE_ENABLED 71 72 // Only bother with this argument setup if dtrace is available 73 74 #define DTRACE_METHOD_UNLOAD_PROBE(method) \ 75 { \ 76 Method* m = (method); \ 77 if (m != NULL) { \ 78 Symbol* klass_name = m->klass_name(); \ 79 Symbol* name = m->name(); \ 80 Symbol* signature = m->signature(); \ 81 HOTSPOT_COMPILED_METHOD_UNLOAD( \ 82 (char *) klass_name->bytes(), klass_name->utf8_length(), \ 83 (char *) name->bytes(), name->utf8_length(), \ 84 (char *) signature->bytes(), signature->utf8_length()); \ 85 } \ 86 } 87 88 #else // ndef DTRACE_ENABLED 89 90 #define DTRACE_METHOD_UNLOAD_PROBE(method) 91 92 #endif 93 94 //--------------------------------------------------------------------------------- 95 // NMethod statistics 96 // They are printed under various flags, including: 97 // PrintC1Statistics, PrintOptoStatistics, LogVMOutput, and LogCompilation. 98 // (In the latter two cases, they like other stats are printed to the log only.) 99 100 #ifndef PRODUCT 101 // These variables are put into one block to reduce relocations 102 // and make it simpler to print from the debugger. 103 struct java_nmethod_stats_struct { 104 int nmethod_count; 105 int total_size; 106 int relocation_size; 107 int consts_size; 108 int insts_size; 109 int stub_size; 110 int scopes_data_size; 111 int scopes_pcs_size; 112 int dependencies_size; 113 int handler_table_size; 114 int nul_chk_table_size; 115 int oops_size; 116 int metadata_size; 117 118 void note_nmethod(nmethod* nm) { 119 nmethod_count += 1; 120 total_size += nm->size(); 121 relocation_size += nm->relocation_size(); 122 consts_size += nm->consts_size(); 123 insts_size += nm->insts_size(); 124 stub_size += nm->stub_size(); 125 oops_size += nm->oops_size(); 126 metadata_size += nm->metadata_size(); 127 scopes_data_size += nm->scopes_data_size(); 128 scopes_pcs_size += nm->scopes_pcs_size(); 129 dependencies_size += nm->dependencies_size(); 130 handler_table_size += nm->handler_table_size(); 131 nul_chk_table_size += nm->nul_chk_table_size(); 132 } 133 void print_nmethod_stats(const char* name) { 134 if (nmethod_count == 0) return; 135 tty->print_cr("Statistics for %d bytecoded nmethods for %s:", nmethod_count, name); 136 if (total_size != 0) tty->print_cr(" total in heap = %d", total_size); 137 if (nmethod_count != 0) tty->print_cr(" header = " SIZE_FORMAT, nmethod_count * sizeof(nmethod)); 138 if (relocation_size != 0) tty->print_cr(" relocation = %d", relocation_size); 139 if (consts_size != 0) tty->print_cr(" constants = %d", consts_size); 140 if (insts_size != 0) tty->print_cr(" main code = %d", insts_size); 141 if (stub_size != 0) tty->print_cr(" stub code = %d", stub_size); 142 if (oops_size != 0) tty->print_cr(" oops = %d", oops_size); 143 if (metadata_size != 0) tty->print_cr(" metadata = %d", metadata_size); 144 if (scopes_data_size != 0) tty->print_cr(" scopes data = %d", scopes_data_size); 145 if (scopes_pcs_size != 0) tty->print_cr(" scopes pcs = %d", scopes_pcs_size); 146 if (dependencies_size != 0) tty->print_cr(" dependencies = %d", dependencies_size); 147 if (handler_table_size != 0) tty->print_cr(" handler table = %d", handler_table_size); 148 if (nul_chk_table_size != 0) tty->print_cr(" nul chk table = %d", nul_chk_table_size); 149 } 150 }; 151 152 struct native_nmethod_stats_struct { 153 int native_nmethod_count; 154 int native_total_size; 155 int native_relocation_size; 156 int native_insts_size; 157 int native_oops_size; 158 int native_metadata_size; 159 void note_native_nmethod(nmethod* nm) { 160 native_nmethod_count += 1; 161 native_total_size += nm->size(); 162 native_relocation_size += nm->relocation_size(); 163 native_insts_size += nm->insts_size(); 164 native_oops_size += nm->oops_size(); 165 native_metadata_size += nm->metadata_size(); 166 } 167 void print_native_nmethod_stats() { 168 if (native_nmethod_count == 0) return; 169 tty->print_cr("Statistics for %d native nmethods:", native_nmethod_count); 170 if (native_total_size != 0) tty->print_cr(" N. total size = %d", native_total_size); 171 if (native_relocation_size != 0) tty->print_cr(" N. relocation = %d", native_relocation_size); 172 if (native_insts_size != 0) tty->print_cr(" N. main code = %d", native_insts_size); 173 if (native_oops_size != 0) tty->print_cr(" N. oops = %d", native_oops_size); 174 if (native_metadata_size != 0) tty->print_cr(" N. metadata = %d", native_metadata_size); 175 } 176 }; 177 178 struct pc_nmethod_stats_struct { 179 int pc_desc_resets; // number of resets (= number of caches) 180 int pc_desc_queries; // queries to nmethod::find_pc_desc 181 int pc_desc_approx; // number of those which have approximate true 182 int pc_desc_repeats; // number of _pc_descs[0] hits 183 int pc_desc_hits; // number of LRU cache hits 184 int pc_desc_tests; // total number of PcDesc examinations 185 int pc_desc_searches; // total number of quasi-binary search steps 186 int pc_desc_adds; // number of LUR cache insertions 187 188 void print_pc_stats() { 189 tty->print_cr("PcDesc Statistics: %d queries, %.2f comparisons per query", 190 pc_desc_queries, 191 (double)(pc_desc_tests + pc_desc_searches) 192 / pc_desc_queries); 193 tty->print_cr(" caches=%d queries=%d/%d, hits=%d+%d, tests=%d+%d, adds=%d", 194 pc_desc_resets, 195 pc_desc_queries, pc_desc_approx, 196 pc_desc_repeats, pc_desc_hits, 197 pc_desc_tests, pc_desc_searches, pc_desc_adds); 198 } 199 }; 200 201 #ifdef COMPILER1 202 static java_nmethod_stats_struct c1_java_nmethod_stats; 203 #endif 204 #ifdef COMPILER2 205 static java_nmethod_stats_struct c2_java_nmethod_stats; 206 #endif 207 #if INCLUDE_JVMCI 208 static java_nmethod_stats_struct jvmci_java_nmethod_stats; 209 #endif 210 static java_nmethod_stats_struct unknown_java_nmethod_stats; 211 212 static native_nmethod_stats_struct native_nmethod_stats; 213 static pc_nmethod_stats_struct pc_nmethod_stats; 214 215 static void note_java_nmethod(nmethod* nm) { 216 #ifdef COMPILER1 217 if (nm->is_compiled_by_c1()) { 218 c1_java_nmethod_stats.note_nmethod(nm); 219 } else 220 #endif 221 #ifdef COMPILER2 222 if (nm->is_compiled_by_c2()) { 223 c2_java_nmethod_stats.note_nmethod(nm); 224 } else 225 #endif 226 #if INCLUDE_JVMCI 227 if (nm->is_compiled_by_jvmci()) { 228 jvmci_java_nmethod_stats.note_nmethod(nm); 229 } else 230 #endif 231 { 232 unknown_java_nmethod_stats.note_nmethod(nm); 233 } 234 } 235 #endif // !PRODUCT 236 237 //--------------------------------------------------------------------------------- 238 239 240 ExceptionCache::ExceptionCache(Handle exception, address pc, address handler) { 241 assert(pc != NULL, "Must be non null"); 242 assert(exception.not_null(), "Must be non null"); 243 assert(handler != NULL, "Must be non null"); 244 245 _count = 0; 246 _exception_type = exception->klass(); 247 _next = NULL; 248 _purge_list_next = NULL; 249 250 add_address_and_handler(pc,handler); 251 } 252 253 254 address ExceptionCache::match(Handle exception, address pc) { 255 assert(pc != NULL,"Must be non null"); 256 assert(exception.not_null(),"Must be non null"); 257 if (exception->klass() == exception_type()) { 258 return (test_address(pc)); 259 } 260 261 return NULL; 262 } 263 264 265 bool ExceptionCache::match_exception_with_space(Handle exception) { 266 assert(exception.not_null(),"Must be non null"); 267 if (exception->klass() == exception_type() && count() < cache_size) { 268 return true; 269 } 270 return false; 271 } 272 273 274 address ExceptionCache::test_address(address addr) { 275 int limit = count(); 276 for (int i = 0; i < limit; i++) { 277 if (pc_at(i) == addr) { 278 return handler_at(i); 279 } 280 } 281 return NULL; 282 } 283 284 285 bool ExceptionCache::add_address_and_handler(address addr, address handler) { 286 if (test_address(addr) == handler) return true; 287 288 int index = count(); 289 if (index < cache_size) { 290 set_pc_at(index, addr); 291 set_handler_at(index, handler); 292 increment_count(); 293 return true; 294 } 295 return false; 296 } 297 298 ExceptionCache* ExceptionCache::next() { 299 return Atomic::load(&_next); 300 } 301 302 void ExceptionCache::set_next(ExceptionCache *ec) { 303 Atomic::store(ec, &_next); 304 } 305 306 //----------------------------------------------------------------------------- 307 308 309 // Helper used by both find_pc_desc methods. 310 static inline bool match_desc(PcDesc* pc, int pc_offset, bool approximate) { 311 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_tests); 312 if (!approximate) 313 return pc->pc_offset() == pc_offset; 314 else 315 return (pc-1)->pc_offset() < pc_offset && pc_offset <= pc->pc_offset(); 316 } 317 318 void PcDescCache::reset_to(PcDesc* initial_pc_desc) { 319 if (initial_pc_desc == NULL) { 320 _pc_descs[0] = NULL; // native method; no PcDescs at all 321 return; 322 } 323 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_resets); 324 // reset the cache by filling it with benign (non-null) values 325 assert(initial_pc_desc->pc_offset() < 0, "must be sentinel"); 326 for (int i = 0; i < cache_size; i++) 327 _pc_descs[i] = initial_pc_desc; 328 } 329 330 PcDesc* PcDescCache::find_pc_desc(int pc_offset, bool approximate) { 331 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_queries); 332 NOT_PRODUCT(if (approximate) ++pc_nmethod_stats.pc_desc_approx); 333 334 // Note: one might think that caching the most recently 335 // read value separately would be a win, but one would be 336 // wrong. When many threads are updating it, the cache 337 // line it's in would bounce between caches, negating 338 // any benefit. 339 340 // In order to prevent race conditions do not load cache elements 341 // repeatedly, but use a local copy: 342 PcDesc* res; 343 344 // Step one: Check the most recently added value. 345 res = _pc_descs[0]; 346 if (res == NULL) return NULL; // native method; no PcDescs at all 347 if (match_desc(res, pc_offset, approximate)) { 348 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_repeats); 349 return res; 350 } 351 352 // Step two: Check the rest of the LRU cache. 353 for (int i = 1; i < cache_size; ++i) { 354 res = _pc_descs[i]; 355 if (res->pc_offset() < 0) break; // optimization: skip empty cache 356 if (match_desc(res, pc_offset, approximate)) { 357 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_hits); 358 return res; 359 } 360 } 361 362 // Report failure. 363 return NULL; 364 } 365 366 void PcDescCache::add_pc_desc(PcDesc* pc_desc) { 367 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_adds); 368 // Update the LRU cache by shifting pc_desc forward. 369 for (int i = 0; i < cache_size; i++) { 370 PcDesc* next = _pc_descs[i]; 371 _pc_descs[i] = pc_desc; 372 pc_desc = next; 373 } 374 } 375 376 // adjust pcs_size so that it is a multiple of both oopSize and 377 // sizeof(PcDesc) (assumes that if sizeof(PcDesc) is not a multiple 378 // of oopSize, then 2*sizeof(PcDesc) is) 379 static int adjust_pcs_size(int pcs_size) { 380 int nsize = align_up(pcs_size, oopSize); 381 if ((nsize % sizeof(PcDesc)) != 0) { 382 nsize = pcs_size + sizeof(PcDesc); 383 } 384 assert((nsize % oopSize) == 0, "correct alignment"); 385 return nsize; 386 } 387 388 389 int nmethod::total_size() const { 390 return 391 consts_size() + 392 insts_size() + 393 stub_size() + 394 scopes_data_size() + 395 scopes_pcs_size() + 396 handler_table_size() + 397 nul_chk_table_size(); 398 } 399 400 address* nmethod::orig_pc_addr(const frame* fr) { 401 return (address*) ((address)fr->unextended_sp() + _orig_pc_offset); 402 } 403 404 const char* nmethod::compile_kind() const { 405 if (is_osr_method()) return "osr"; 406 if (method() != NULL && is_native_method()) return "c2n"; 407 return NULL; 408 } 409 410 // Fill in default values for various flag fields 411 void nmethod::init_defaults() { 412 _state = not_installed; 413 _has_flushed_dependencies = 0; 414 _lock_count = 0; 415 _stack_traversal_mark = 0; 416 _unload_reported = false; // jvmti state 417 _is_far_code = false; // nmethods are located in CodeCache 418 419 #ifdef ASSERT 420 _oops_are_stale = false; 421 #endif 422 423 _oops_do_mark_link = NULL; 424 _jmethod_id = NULL; 425 _osr_link = NULL; 426 _scavenge_root_link = NULL; 427 _scavenge_root_state = 0; 428 #if INCLUDE_RTM_OPT 429 _rtm_state = NoRTM; 430 #endif 431 #if INCLUDE_JVMCI 432 _jvmci_installed_code = NULL; 433 _speculation_log = NULL; 434 _jvmci_installed_code_triggers_invalidation = false; 435 #endif 436 } 437 438 nmethod* nmethod::new_native_nmethod(const methodHandle& method, 439 int compile_id, 440 CodeBuffer *code_buffer, 441 int vep_offset, 442 int frame_complete, 443 int frame_size, 444 ByteSize basic_lock_owner_sp_offset, 445 ByteSize basic_lock_sp_offset, 446 OopMapSet* oop_maps) { 447 code_buffer->finalize_oop_references(method); 448 // create nmethod 449 nmethod* nm = NULL; 450 { 451 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 452 int native_nmethod_size = CodeBlob::allocation_size(code_buffer, sizeof(nmethod)); 453 CodeOffsets offsets; 454 offsets.set_value(CodeOffsets::Verified_Entry, vep_offset); 455 offsets.set_value(CodeOffsets::Frame_Complete, frame_complete); 456 nm = new (native_nmethod_size, CompLevel_none) nmethod(method(), compiler_none, native_nmethod_size, 457 compile_id, &offsets, 458 code_buffer, frame_size, 459 basic_lock_owner_sp_offset, 460 basic_lock_sp_offset, oop_maps); 461 NOT_PRODUCT(if (nm != NULL) native_nmethod_stats.note_native_nmethod(nm)); 462 } 463 464 if (nm != NULL) { 465 // verify nmethod 466 debug_only(nm->verify();) // might block 467 468 nm->log_new_nmethod(); 469 nm->make_in_use(); 470 } 471 return nm; 472 } 473 474 nmethod* nmethod::new_nmethod(const methodHandle& method, 475 int compile_id, 476 int entry_bci, 477 CodeOffsets* offsets, 478 int orig_pc_offset, 479 DebugInformationRecorder* debug_info, 480 Dependencies* dependencies, 481 CodeBuffer* code_buffer, int frame_size, 482 OopMapSet* oop_maps, 483 ExceptionHandlerTable* handler_table, 484 ImplicitExceptionTable* nul_chk_table, 485 AbstractCompiler* compiler, 486 int comp_level 487 #if INCLUDE_JVMCI 488 , jweak installed_code, 489 jweak speculationLog 490 #endif 491 ) 492 { 493 assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR"); 494 code_buffer->finalize_oop_references(method); 495 // create nmethod 496 nmethod* nm = NULL; 497 { MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 498 int nmethod_size = 499 CodeBlob::allocation_size(code_buffer, sizeof(nmethod)) 500 + adjust_pcs_size(debug_info->pcs_size()) 501 + align_up((int)dependencies->size_in_bytes(), oopSize) 502 + align_up(handler_table->size_in_bytes() , oopSize) 503 + align_up(nul_chk_table->size_in_bytes() , oopSize) 504 + align_up(debug_info->data_size() , oopSize); 505 506 nm = new (nmethod_size, comp_level) 507 nmethod(method(), compiler->type(), nmethod_size, compile_id, entry_bci, offsets, 508 orig_pc_offset, debug_info, dependencies, code_buffer, frame_size, 509 oop_maps, 510 handler_table, 511 nul_chk_table, 512 compiler, 513 comp_level 514 #if INCLUDE_JVMCI 515 , installed_code, 516 speculationLog 517 #endif 518 ); 519 520 if (nm != NULL) { 521 // To make dependency checking during class loading fast, record 522 // the nmethod dependencies in the classes it is dependent on. 523 // This allows the dependency checking code to simply walk the 524 // class hierarchy above the loaded class, checking only nmethods 525 // which are dependent on those classes. The slow way is to 526 // check every nmethod for dependencies which makes it linear in 527 // the number of methods compiled. For applications with a lot 528 // classes the slow way is too slow. 529 for (Dependencies::DepStream deps(nm); deps.next(); ) { 530 if (deps.type() == Dependencies::call_site_target_value) { 531 // CallSite dependencies are managed on per-CallSite instance basis. 532 oop call_site = deps.argument_oop(0); 533 MethodHandles::add_dependent_nmethod(call_site, nm); 534 } else { 535 Klass* klass = deps.context_type(); 536 if (klass == NULL) { 537 continue; // ignore things like evol_method 538 } 539 // record this nmethod as dependent on this klass 540 InstanceKlass::cast(klass)->add_dependent_nmethod(nm); 541 } 542 } 543 NOT_PRODUCT(if (nm != NULL) note_java_nmethod(nm)); 544 } 545 } 546 // Do verification and logging outside CodeCache_lock. 547 if (nm != NULL) { 548 // Safepoints in nmethod::verify aren't allowed because nm hasn't been installed yet. 549 DEBUG_ONLY(nm->verify();) 550 nm->log_new_nmethod(); 551 } 552 return nm; 553 } 554 555 // For native wrappers 556 nmethod::nmethod( 557 Method* method, 558 CompilerType type, 559 int nmethod_size, 560 int compile_id, 561 CodeOffsets* offsets, 562 CodeBuffer* code_buffer, 563 int frame_size, 564 ByteSize basic_lock_owner_sp_offset, 565 ByteSize basic_lock_sp_offset, 566 OopMapSet* oop_maps ) 567 : CompiledMethod(method, "native nmethod", type, nmethod_size, sizeof(nmethod), code_buffer, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps, false), 568 _is_unloading_state(0), 569 _native_receiver_sp_offset(basic_lock_owner_sp_offset), 570 _native_basic_lock_sp_offset(basic_lock_sp_offset) 571 { 572 { 573 int scopes_data_offset = 0; 574 int deoptimize_offset = 0; 575 int deoptimize_mh_offset = 0; 576 577 debug_only(NoSafepointVerifier nsv;) 578 assert_locked_or_safepoint(CodeCache_lock); 579 580 init_defaults(); 581 _entry_bci = InvocationEntryBci; 582 // We have no exception handler or deopt handler make the 583 // values something that will never match a pc like the nmethod vtable entry 584 _exception_offset = 0; 585 _orig_pc_offset = 0; 586 587 _consts_offset = data_offset(); 588 _stub_offset = data_offset(); 589 _oops_offset = data_offset(); 590 _metadata_offset = _oops_offset + align_up(code_buffer->total_oop_size(), oopSize); 591 scopes_data_offset = _metadata_offset + align_up(code_buffer->total_metadata_size(), wordSize); 592 _scopes_pcs_offset = scopes_data_offset; 593 _dependencies_offset = _scopes_pcs_offset; 594 _handler_table_offset = _dependencies_offset; 595 _nul_chk_table_offset = _handler_table_offset; 596 _nmethod_end_offset = _nul_chk_table_offset; 597 _compile_id = compile_id; 598 _comp_level = CompLevel_none; 599 _entry_point = code_begin() + offsets->value(CodeOffsets::Entry); 600 _verified_entry_point = code_begin() + offsets->value(CodeOffsets::Verified_Entry); 601 _osr_entry_point = NULL; 602 _exception_cache = NULL; 603 _pc_desc_container.reset_to(NULL); 604 _hotness_counter = NMethodSweeper::hotness_counter_reset_val(); 605 606 _scopes_data_begin = (address) this + scopes_data_offset; 607 _deopt_handler_begin = (address) this + deoptimize_offset; 608 _deopt_mh_handler_begin = (address) this + deoptimize_mh_offset; 609 610 code_buffer->copy_code_and_locs_to(this); 611 code_buffer->copy_values_to(this); 612 613 clear_unloading_state(); 614 if (ScavengeRootsInCode) { 615 Universe::heap()->register_nmethod(this); 616 } 617 debug_only(Universe::heap()->verify_nmethod(this)); 618 CodeCache::commit(this); 619 } 620 621 if (PrintNativeNMethods || PrintDebugInfo || PrintRelocations || PrintDependencies) { 622 ttyLocker ttyl; // keep the following output all in one block 623 // This output goes directly to the tty, not the compiler log. 624 // To enable tools to match it up with the compilation activity, 625 // be sure to tag this tty output with the compile ID. 626 if (xtty != NULL) { 627 xtty->begin_head("print_native_nmethod"); 628 xtty->method(_method); 629 xtty->stamp(); 630 xtty->end_head(" address='" INTPTR_FORMAT "'", (intptr_t) this); 631 } 632 // print the header part first 633 print(); 634 // then print the requested information 635 if (PrintNativeNMethods) { 636 print_code(); 637 if (oop_maps != NULL) { 638 oop_maps->print(); 639 } 640 } 641 if (PrintRelocations) { 642 print_relocations(); 643 } 644 if (xtty != NULL) { 645 xtty->tail("print_native_nmethod"); 646 } 647 } 648 } 649 650 void* nmethod::operator new(size_t size, int nmethod_size, int comp_level) throw () { 651 return CodeCache::allocate(nmethod_size, CodeCache::get_code_blob_type(comp_level)); 652 } 653 654 nmethod::nmethod( 655 Method* method, 656 CompilerType type, 657 int nmethod_size, 658 int compile_id, 659 int entry_bci, 660 CodeOffsets* offsets, 661 int orig_pc_offset, 662 DebugInformationRecorder* debug_info, 663 Dependencies* dependencies, 664 CodeBuffer *code_buffer, 665 int frame_size, 666 OopMapSet* oop_maps, 667 ExceptionHandlerTable* handler_table, 668 ImplicitExceptionTable* nul_chk_table, 669 AbstractCompiler* compiler, 670 int comp_level 671 #if INCLUDE_JVMCI 672 , jweak installed_code, 673 jweak speculation_log 674 #endif 675 ) 676 : CompiledMethod(method, "nmethod", type, nmethod_size, sizeof(nmethod), code_buffer, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps, false), 677 _is_unloading_state(0), 678 _native_receiver_sp_offset(in_ByteSize(-1)), 679 _native_basic_lock_sp_offset(in_ByteSize(-1)) 680 { 681 assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR"); 682 { 683 debug_only(NoSafepointVerifier nsv;) 684 assert_locked_or_safepoint(CodeCache_lock); 685 686 _deopt_handler_begin = (address) this; 687 _deopt_mh_handler_begin = (address) this; 688 689 init_defaults(); 690 _entry_bci = entry_bci; 691 _compile_id = compile_id; 692 _comp_level = comp_level; 693 _orig_pc_offset = orig_pc_offset; 694 _hotness_counter = NMethodSweeper::hotness_counter_reset_val(); 695 696 // Section offsets 697 _consts_offset = content_offset() + code_buffer->total_offset_of(code_buffer->consts()); 698 _stub_offset = content_offset() + code_buffer->total_offset_of(code_buffer->stubs()); 699 set_ctable_begin(header_begin() + _consts_offset); 700 701 #if INCLUDE_JVMCI 702 _jvmci_installed_code = installed_code; 703 _speculation_log = speculation_log; 704 oop obj = JNIHandles::resolve(installed_code); 705 if (obj == NULL || (obj->is_a(HotSpotNmethod::klass()) && HotSpotNmethod::isDefault(obj))) { 706 _jvmci_installed_code_triggers_invalidation = false; 707 } else { 708 _jvmci_installed_code_triggers_invalidation = true; 709 } 710 711 if (compiler->is_jvmci()) { 712 // JVMCI might not produce any stub sections 713 if (offsets->value(CodeOffsets::Exceptions) != -1) { 714 _exception_offset = code_offset() + offsets->value(CodeOffsets::Exceptions); 715 } else { 716 _exception_offset = -1; 717 } 718 if (offsets->value(CodeOffsets::Deopt) != -1) { 719 _deopt_handler_begin = (address) this + code_offset() + offsets->value(CodeOffsets::Deopt); 720 } else { 721 _deopt_handler_begin = NULL; 722 } 723 if (offsets->value(CodeOffsets::DeoptMH) != -1) { 724 _deopt_mh_handler_begin = (address) this + code_offset() + offsets->value(CodeOffsets::DeoptMH); 725 } else { 726 _deopt_mh_handler_begin = NULL; 727 } 728 } else { 729 #endif 730 // Exception handler and deopt handler are in the stub section 731 assert(offsets->value(CodeOffsets::Exceptions) != -1, "must be set"); 732 assert(offsets->value(CodeOffsets::Deopt ) != -1, "must be set"); 733 734 _exception_offset = _stub_offset + offsets->value(CodeOffsets::Exceptions); 735 _deopt_handler_begin = (address) this + _stub_offset + offsets->value(CodeOffsets::Deopt); 736 if (offsets->value(CodeOffsets::DeoptMH) != -1) { 737 _deopt_mh_handler_begin = (address) this + _stub_offset + offsets->value(CodeOffsets::DeoptMH); 738 } else { 739 _deopt_mh_handler_begin = NULL; 740 #if INCLUDE_JVMCI 741 } 742 #endif 743 } 744 if (offsets->value(CodeOffsets::UnwindHandler) != -1) { 745 _unwind_handler_offset = code_offset() + offsets->value(CodeOffsets::UnwindHandler); 746 } else { 747 _unwind_handler_offset = -1; 748 } 749 750 _oops_offset = data_offset(); 751 _metadata_offset = _oops_offset + align_up(code_buffer->total_oop_size(), oopSize); 752 int scopes_data_offset = _metadata_offset + align_up(code_buffer->total_metadata_size(), wordSize); 753 754 _scopes_pcs_offset = scopes_data_offset + align_up(debug_info->data_size (), oopSize); 755 _dependencies_offset = _scopes_pcs_offset + adjust_pcs_size(debug_info->pcs_size()); 756 _handler_table_offset = _dependencies_offset + align_up((int)dependencies->size_in_bytes (), oopSize); 757 _nul_chk_table_offset = _handler_table_offset + align_up(handler_table->size_in_bytes(), oopSize); 758 _nmethod_end_offset = _nul_chk_table_offset + align_up(nul_chk_table->size_in_bytes(), oopSize); 759 _entry_point = code_begin() + offsets->value(CodeOffsets::Entry); 760 _verified_entry_point = code_begin() + offsets->value(CodeOffsets::Verified_Entry); 761 _osr_entry_point = code_begin() + offsets->value(CodeOffsets::OSR_Entry); 762 _exception_cache = NULL; 763 764 _scopes_data_begin = (address) this + scopes_data_offset; 765 766 _pc_desc_container.reset_to(scopes_pcs_begin()); 767 768 code_buffer->copy_code_and_locs_to(this); 769 // Copy contents of ScopeDescRecorder to nmethod 770 code_buffer->copy_values_to(this); 771 debug_info->copy_to(this); 772 dependencies->copy_to(this); 773 clear_unloading_state(); 774 if (ScavengeRootsInCode) { 775 Universe::heap()->register_nmethod(this); 776 } 777 debug_only(Universe::heap()->verify_nmethod(this)); 778 779 CodeCache::commit(this); 780 781 // Copy contents of ExceptionHandlerTable to nmethod 782 handler_table->copy_to(this); 783 nul_chk_table->copy_to(this); 784 785 // we use the information of entry points to find out if a method is 786 // static or non static 787 assert(compiler->is_c2() || compiler->is_jvmci() || 788 _method->is_static() == (entry_point() == _verified_entry_point), 789 " entry points must be same for static methods and vice versa"); 790 } 791 } 792 793 // Print a short set of xml attributes to identify this nmethod. The 794 // output should be embedded in some other element. 795 void nmethod::log_identity(xmlStream* log) const { 796 log->print(" compile_id='%d'", compile_id()); 797 const char* nm_kind = compile_kind(); 798 if (nm_kind != NULL) log->print(" compile_kind='%s'", nm_kind); 799 log->print(" compiler='%s'", compiler_name()); 800 if (TieredCompilation) { 801 log->print(" level='%d'", comp_level()); 802 } 803 #if INCLUDE_JVMCI 804 char buffer[O_BUFLEN]; 805 char* jvmci_name = jvmci_installed_code_name(buffer, O_BUFLEN); 806 if (jvmci_name != NULL) { 807 log->print(" jvmci_installed_code_name='"); 808 log->text("%s", jvmci_name); 809 log->print("'"); 810 } 811 #endif 812 } 813 814 815 #define LOG_OFFSET(log, name) \ 816 if (p2i(name##_end()) - p2i(name##_begin())) \ 817 log->print(" " XSTR(name) "_offset='" INTX_FORMAT "'" , \ 818 p2i(name##_begin()) - p2i(this)) 819 820 821 void nmethod::log_new_nmethod() const { 822 if (LogCompilation && xtty != NULL) { 823 ttyLocker ttyl; 824 HandleMark hm; 825 xtty->begin_elem("nmethod"); 826 log_identity(xtty); 827 xtty->print(" entry='" INTPTR_FORMAT "' size='%d'", p2i(code_begin()), size()); 828 xtty->print(" address='" INTPTR_FORMAT "'", p2i(this)); 829 830 LOG_OFFSET(xtty, relocation); 831 LOG_OFFSET(xtty, consts); 832 LOG_OFFSET(xtty, insts); 833 LOG_OFFSET(xtty, stub); 834 LOG_OFFSET(xtty, scopes_data); 835 LOG_OFFSET(xtty, scopes_pcs); 836 LOG_OFFSET(xtty, dependencies); 837 LOG_OFFSET(xtty, handler_table); 838 LOG_OFFSET(xtty, nul_chk_table); 839 LOG_OFFSET(xtty, oops); 840 LOG_OFFSET(xtty, metadata); 841 842 xtty->method(method()); 843 xtty->stamp(); 844 xtty->end_elem(); 845 } 846 } 847 848 #undef LOG_OFFSET 849 850 851 // Print out more verbose output usually for a newly created nmethod. 852 void nmethod::print_on(outputStream* st, const char* msg) const { 853 if (st != NULL) { 854 ttyLocker ttyl; 855 if (WizardMode) { 856 CompileTask::print(st, this, msg, /*short_form:*/ true); 857 st->print_cr(" (" INTPTR_FORMAT ")", p2i(this)); 858 } else { 859 CompileTask::print(st, this, msg, /*short_form:*/ false); 860 } 861 } 862 } 863 864 void nmethod::maybe_print_nmethod(DirectiveSet* directive) { 865 bool printnmethods = directive->PrintAssemblyOption || directive->PrintNMethodsOption; 866 if (printnmethods || PrintDebugInfo || PrintRelocations || PrintDependencies || PrintExceptionHandlers) { 867 print_nmethod(printnmethods); 868 } 869 } 870 871 void nmethod::print_nmethod(bool printmethod) { 872 ttyLocker ttyl; // keep the following output all in one block 873 if (xtty != NULL) { 874 xtty->begin_head("print_nmethod"); 875 xtty->stamp(); 876 xtty->end_head(); 877 } 878 // print the header part first 879 print(); 880 // then print the requested information 881 if (printmethod) { 882 print_code(); 883 print_pcs(); 884 if (oop_maps()) { 885 oop_maps()->print(); 886 } 887 } 888 if (printmethod || PrintDebugInfo || CompilerOracle::has_option_string(_method, "PrintDebugInfo")) { 889 print_scopes(); 890 } 891 if (printmethod || PrintRelocations || CompilerOracle::has_option_string(_method, "PrintRelocations")) { 892 print_relocations(); 893 } 894 if (printmethod || PrintDependencies || CompilerOracle::has_option_string(_method, "PrintDependencies")) { 895 print_dependencies(); 896 } 897 if (printmethod || PrintExceptionHandlers) { 898 print_handler_table(); 899 print_nul_chk_table(); 900 } 901 if (printmethod) { 902 print_recorded_oops(); 903 print_recorded_metadata(); 904 } 905 if (xtty != NULL) { 906 xtty->tail("print_nmethod"); 907 } 908 } 909 910 911 // Promote one word from an assembly-time handle to a live embedded oop. 912 inline void nmethod::initialize_immediate_oop(oop* dest, jobject handle) { 913 if (handle == NULL || 914 // As a special case, IC oops are initialized to 1 or -1. 915 handle == (jobject) Universe::non_oop_word()) { 916 (*dest) = (oop) handle; 917 } else { 918 (*dest) = JNIHandles::resolve_non_null(handle); 919 } 920 } 921 922 923 // Have to have the same name because it's called by a template 924 void nmethod::copy_values(GrowableArray<jobject>* array) { 925 int length = array->length(); 926 assert((address)(oops_begin() + length) <= (address)oops_end(), "oops big enough"); 927 oop* dest = oops_begin(); 928 for (int index = 0 ; index < length; index++) { 929 initialize_immediate_oop(&dest[index], array->at(index)); 930 } 931 932 // Now we can fix up all the oops in the code. We need to do this 933 // in the code because the assembler uses jobjects as placeholders. 934 // The code and relocations have already been initialized by the 935 // CodeBlob constructor, so it is valid even at this early point to 936 // iterate over relocations and patch the code. 937 fix_oop_relocations(NULL, NULL, /*initialize_immediates=*/ true); 938 } 939 940 void nmethod::copy_values(GrowableArray<Metadata*>* array) { 941 int length = array->length(); 942 assert((address)(metadata_begin() + length) <= (address)metadata_end(), "big enough"); 943 Metadata** dest = metadata_begin(); 944 for (int index = 0 ; index < length; index++) { 945 dest[index] = array->at(index); 946 } 947 } 948 949 void nmethod::fix_oop_relocations(address begin, address end, bool initialize_immediates) { 950 // re-patch all oop-bearing instructions, just in case some oops moved 951 RelocIterator iter(this, begin, end); 952 while (iter.next()) { 953 if (iter.type() == relocInfo::oop_type) { 954 oop_Relocation* reloc = iter.oop_reloc(); 955 if (initialize_immediates && reloc->oop_is_immediate()) { 956 oop* dest = reloc->oop_addr(); 957 initialize_immediate_oop(dest, (jobject) *dest); 958 } 959 // Refresh the oop-related bits of this instruction. 960 reloc->fix_oop_relocation(); 961 } else if (iter.type() == relocInfo::metadata_type) { 962 metadata_Relocation* reloc = iter.metadata_reloc(); 963 reloc->fix_metadata_relocation(); 964 } 965 } 966 } 967 968 969 void nmethod::verify_clean_inline_caches() { 970 assert(CompiledICLocker::is_safe(this), "mt unsafe call"); 971 972 ResourceMark rm; 973 RelocIterator iter(this, oops_reloc_begin()); 974 while(iter.next()) { 975 switch(iter.type()) { 976 case relocInfo::virtual_call_type: 977 case relocInfo::opt_virtual_call_type: { 978 CompiledIC *ic = CompiledIC_at(&iter); 979 // Ok, to lookup references to zombies here 980 CodeBlob *cb = CodeCache::find_blob_unsafe(ic->ic_destination()); 981 assert(cb != NULL, "destination not in CodeBlob?"); 982 nmethod* nm = cb->as_nmethod_or_null(); 983 if( nm != NULL ) { 984 // Verify that inline caches pointing to both zombie and not_entrant methods are clean 985 if (!nm->is_in_use() || (nm->method()->code() != nm)) { 986 assert(ic->is_clean(), "IC should be clean"); 987 } 988 } 989 break; 990 } 991 case relocInfo::static_call_type: { 992 CompiledStaticCall *csc = compiledStaticCall_at(iter.reloc()); 993 CodeBlob *cb = CodeCache::find_blob_unsafe(csc->destination()); 994 assert(cb != NULL, "destination not in CodeBlob?"); 995 nmethod* nm = cb->as_nmethod_or_null(); 996 if( nm != NULL ) { 997 // Verify that inline caches pointing to both zombie and not_entrant methods are clean 998 if (!nm->is_in_use() || (nm->method()->code() != nm)) { 999 assert(csc->is_clean(), "IC should be clean"); 1000 } 1001 } 1002 break; 1003 } 1004 default: 1005 break; 1006 } 1007 } 1008 } 1009 1010 // This is a private interface with the sweeper. 1011 void nmethod::mark_as_seen_on_stack() { 1012 assert(is_alive(), "Must be an alive method"); 1013 // Set the traversal mark to ensure that the sweeper does 2 1014 // cleaning passes before moving to zombie. 1015 set_stack_traversal_mark(NMethodSweeper::traversal_count()); 1016 } 1017 1018 // Tell if a non-entrant method can be converted to a zombie (i.e., 1019 // there are no activations on the stack, not in use by the VM, 1020 // and not in use by the ServiceThread) 1021 bool nmethod::can_convert_to_zombie() { 1022 // Note that this is called when the sweeper has observed the nmethod to be 1023 // not_entrant. However, with concurrent code cache unloading, the state 1024 // might have moved on to unloaded if it is_unloading(), due to racing 1025 // concurrent GC threads. 1026 assert(is_not_entrant() || is_unloading(), "must be a non-entrant method"); 1027 1028 // Since the nmethod sweeper only does partial sweep the sweeper's traversal 1029 // count can be greater than the stack traversal count before it hits the 1030 // nmethod for the second time. 1031 // If an is_unloading() nmethod is still not_entrant, then it is not safe to 1032 // convert it to zombie due to GC unloading interactions. However, if it 1033 // has become unloaded, then it is okay to convert such nmethods to zombie. 1034 return stack_traversal_mark() + 1 < NMethodSweeper::traversal_count() && 1035 !is_locked_by_vm() && (!is_unloading() || is_unloaded()); 1036 } 1037 1038 void nmethod::inc_decompile_count() { 1039 if (!is_compiled_by_c2() && !is_compiled_by_jvmci()) return; 1040 // Could be gated by ProfileTraps, but do not bother... 1041 Method* m = method(); 1042 if (m == NULL) return; 1043 MethodData* mdo = m->method_data(); 1044 if (mdo == NULL) return; 1045 // There is a benign race here. See comments in methodData.hpp. 1046 mdo->inc_decompile_count(); 1047 } 1048 1049 void nmethod::make_unloaded() { 1050 post_compiled_method_unload(); 1051 1052 // This nmethod is being unloaded, make sure that dependencies 1053 // recorded in instanceKlasses get flushed. 1054 // Since this work is being done during a GC, defer deleting dependencies from the 1055 // InstanceKlass. 1056 assert(Universe::heap()->is_gc_active() || Thread::current()->is_ConcurrentGC_thread(), 1057 "should only be called during gc"); 1058 flush_dependencies(/*delete_immediately*/false); 1059 1060 // Break cycle between nmethod & method 1061 LogTarget(Trace, class, unload, nmethod) lt; 1062 if (lt.is_enabled()) { 1063 LogStream ls(lt); 1064 ls.print("making nmethod " INTPTR_FORMAT 1065 " unloadable, Method*(" INTPTR_FORMAT 1066 ") ", 1067 p2i(this), p2i(_method)); 1068 ls.cr(); 1069 } 1070 // Unlink the osr method, so we do not look this up again 1071 if (is_osr_method()) { 1072 // Invalidate the osr nmethod only once 1073 if (is_in_use()) { 1074 invalidate_osr_method(); 1075 } 1076 #ifdef ASSERT 1077 if (method() != NULL) { 1078 // Make sure osr nmethod is invalidated, i.e. not on the list 1079 bool found = method()->method_holder()->remove_osr_nmethod(this); 1080 assert(!found, "osr nmethod should have been invalidated"); 1081 } 1082 #endif 1083 } 1084 1085 // If _method is already NULL the Method* is about to be unloaded, 1086 // so we don't have to break the cycle. Note that it is possible to 1087 // have the Method* live here, in case we unload the nmethod because 1088 // it is pointing to some oop (other than the Method*) being unloaded. 1089 if (_method != NULL) { 1090 // OSR methods point to the Method*, but the Method* does not 1091 // point back! 1092 if (_method->code() == this) { 1093 _method->clear_code(); // Break a cycle 1094 } 1095 _method = NULL; // Clear the method of this dead nmethod 1096 } 1097 1098 // Make the class unloaded - i.e., change state and notify sweeper 1099 assert(SafepointSynchronize::is_at_safepoint() || Thread::current()->is_ConcurrentGC_thread(), 1100 "must be at safepoint"); 1101 1102 { 1103 // Clear ICStubs and release any CompiledICHolders. 1104 CompiledICLocker ml(this); 1105 clear_ic_callsites(); 1106 } 1107 1108 // Unregister must be done before the state change 1109 { 1110 MutexLockerEx ml(SafepointSynchronize::is_at_safepoint() ? NULL : CodeCache_lock, 1111 Mutex::_no_safepoint_check_flag); 1112 Universe::heap()->unregister_nmethod(this); 1113 } 1114 1115 // Log the unloading. 1116 log_state_change(); 1117 1118 #if INCLUDE_JVMCI 1119 // The method can only be unloaded after the pointer to the installed code 1120 // Java wrapper is no longer alive. Here we need to clear out this weak 1121 // reference to the dead object. 1122 maybe_invalidate_installed_code(); 1123 #endif 1124 1125 // The Method* is gone at this point 1126 assert(_method == NULL, "Tautology"); 1127 1128 set_osr_link(NULL); 1129 NMethodSweeper::report_state_change(this); 1130 1131 // The release is only needed for compile-time ordering, as accesses 1132 // into the nmethod after the store are not safe due to the sweeper 1133 // being allowed to free it when the store is observed, during 1134 // concurrent nmethod unloading. Therefore, there is no need for 1135 // acquire on the loader side. 1136 OrderAccess::release_store(&_state, (signed char)unloaded); 1137 } 1138 1139 void nmethod::invalidate_osr_method() { 1140 assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod"); 1141 // Remove from list of active nmethods 1142 if (method() != NULL) { 1143 method()->method_holder()->remove_osr_nmethod(this); 1144 } 1145 } 1146 1147 void nmethod::log_state_change() const { 1148 if (LogCompilation) { 1149 if (xtty != NULL) { 1150 ttyLocker ttyl; // keep the following output all in one block 1151 if (_state == unloaded) { 1152 xtty->begin_elem("make_unloaded thread='" UINTX_FORMAT "'", 1153 os::current_thread_id()); 1154 } else { 1155 xtty->begin_elem("make_not_entrant thread='" UINTX_FORMAT "'%s", 1156 os::current_thread_id(), 1157 (_state == zombie ? " zombie='1'" : "")); 1158 } 1159 log_identity(xtty); 1160 xtty->stamp(); 1161 xtty->end_elem(); 1162 } 1163 } 1164 1165 const char *state_msg = _state == zombie ? "made zombie" : "made not entrant"; 1166 CompileTask::print_ul(this, state_msg); 1167 if (PrintCompilation && _state != unloaded) { 1168 print_on(tty, state_msg); 1169 } 1170 } 1171 1172 void nmethod::unlink_from_method(bool acquire_lock) { 1173 // We need to check if both the _code and _from_compiled_code_entry_point 1174 // refer to this nmethod because there is a race in setting these two fields 1175 // in Method* as seen in bugid 4947125. 1176 // If the vep() points to the zombie nmethod, the memory for the nmethod 1177 // could be flushed and the compiler and vtable stubs could still call 1178 // through it. 1179 if (method() != NULL && (method()->code() == this || 1180 method()->from_compiled_entry() == verified_entry_point())) { 1181 method()->clear_code(acquire_lock); 1182 } 1183 } 1184 1185 /** 1186 * Common functionality for both make_not_entrant and make_zombie 1187 */ 1188 bool nmethod::make_not_entrant_or_zombie(int state) { 1189 assert(state == zombie || state == not_entrant, "must be zombie or not_entrant"); 1190 assert(!is_zombie(), "should not already be a zombie"); 1191 1192 if (_state == state) { 1193 // Avoid taking the lock if already in required state. 1194 // This is safe from races because the state is an end-state, 1195 // which the nmethod cannot back out of once entered. 1196 // No need for fencing either. 1197 return false; 1198 } 1199 1200 // Make sure neither the nmethod nor the method is flushed in case of a safepoint in code below. 1201 nmethodLocker nml(this); 1202 methodHandle the_method(method()); 1203 // This can be called while the system is already at a safepoint which is ok 1204 NoSafepointVerifier nsv(true, !SafepointSynchronize::is_at_safepoint()); 1205 1206 // during patching, depending on the nmethod state we must notify the GC that 1207 // code has been unloaded, unregistering it. We cannot do this right while 1208 // holding the Patching_lock because we need to use the CodeCache_lock. This 1209 // would be prone to deadlocks. 1210 // This flag is used to remember whether we need to later lock and unregister. 1211 bool nmethod_needs_unregister = false; 1212 1213 { 1214 // invalidate osr nmethod before acquiring the patching lock since 1215 // they both acquire leaf locks and we don't want a deadlock. 1216 // This logic is equivalent to the logic below for patching the 1217 // verified entry point of regular methods. We check that the 1218 // nmethod is in use to ensure that it is invalidated only once. 1219 if (is_osr_method() && is_in_use()) { 1220 // this effectively makes the osr nmethod not entrant 1221 invalidate_osr_method(); 1222 } 1223 1224 // Enter critical section. Does not block for safepoint. 1225 MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag); 1226 1227 if (_state == state) { 1228 // another thread already performed this transition so nothing 1229 // to do, but return false to indicate this. 1230 return false; 1231 } 1232 1233 // The caller can be calling the method statically or through an inline 1234 // cache call. 1235 if (!is_osr_method() && !is_not_entrant()) { 1236 NativeJump::patch_verified_entry(entry_point(), verified_entry_point(), 1237 SharedRuntime::get_handle_wrong_method_stub()); 1238 } 1239 1240 if (is_in_use() && update_recompile_counts()) { 1241 // It's a true state change, so mark the method as decompiled. 1242 // Do it only for transition from alive. 1243 inc_decompile_count(); 1244 } 1245 1246 // If the state is becoming a zombie, signal to unregister the nmethod with 1247 // the heap. 1248 // This nmethod may have already been unloaded during a full GC. 1249 if ((state == zombie) && !is_unloaded()) { 1250 nmethod_needs_unregister = true; 1251 } 1252 1253 // Must happen before state change. Otherwise we have a race condition in 1254 // nmethod::can_not_entrant_be_converted(). I.e., a method can immediately 1255 // transition its state from 'not_entrant' to 'zombie' without having to wait 1256 // for stack scanning. 1257 if (state == not_entrant) { 1258 mark_as_seen_on_stack(); 1259 OrderAccess::storestore(); // _stack_traversal_mark and _state 1260 } 1261 1262 // Change state 1263 _state = state; 1264 1265 // Log the transition once 1266 log_state_change(); 1267 1268 // Invalidate while holding the patching lock 1269 JVMCI_ONLY(maybe_invalidate_installed_code()); 1270 1271 // Remove nmethod from method. 1272 unlink_from_method(false /* already owns Patching_lock */); 1273 } // leave critical region under Patching_lock 1274 1275 #ifdef ASSERT 1276 if (is_osr_method() && method() != NULL) { 1277 // Make sure osr nmethod is invalidated, i.e. not on the list 1278 bool found = method()->method_holder()->remove_osr_nmethod(this); 1279 assert(!found, "osr nmethod should have been invalidated"); 1280 } 1281 #endif 1282 1283 // When the nmethod becomes zombie it is no longer alive so the 1284 // dependencies must be flushed. nmethods in the not_entrant 1285 // state will be flushed later when the transition to zombie 1286 // happens or they get unloaded. 1287 if (state == zombie) { 1288 { 1289 // Flushing dependencies must be done before any possible 1290 // safepoint can sneak in, otherwise the oops used by the 1291 // dependency logic could have become stale. 1292 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1293 if (nmethod_needs_unregister) { 1294 Universe::heap()->unregister_nmethod(this); 1295 } 1296 flush_dependencies(/*delete_immediately*/true); 1297 } 1298 1299 // Clear ICStubs to prevent back patching stubs of zombie or flushed 1300 // nmethods during the next safepoint (see ICStub::finalize), as well 1301 // as to free up CompiledICHolder resources. 1302 { 1303 CompiledICLocker ml(this); 1304 clear_ic_callsites(); 1305 } 1306 1307 // zombie only - if a JVMTI agent has enabled the CompiledMethodUnload 1308 // event and it hasn't already been reported for this nmethod then 1309 // report it now. The event may have been reported earlier if the GC 1310 // marked it for unloading). JvmtiDeferredEventQueue support means 1311 // we no longer go to a safepoint here. 1312 post_compiled_method_unload(); 1313 1314 #ifdef ASSERT 1315 // It's no longer safe to access the oops section since zombie 1316 // nmethods aren't scanned for GC. 1317 _oops_are_stale = true; 1318 #endif 1319 // the Method may be reclaimed by class unloading now that the 1320 // nmethod is in zombie state 1321 set_method(NULL); 1322 } else { 1323 assert(state == not_entrant, "other cases may need to be handled differently"); 1324 } 1325 1326 if (TraceCreateZombies) { 1327 ResourceMark m; 1328 tty->print_cr("nmethod <" INTPTR_FORMAT "> %s code made %s", p2i(this), this->method() ? this->method()->name_and_sig_as_C_string() : "null", (state == not_entrant) ? "not entrant" : "zombie"); 1329 } 1330 1331 NMethodSweeper::report_state_change(this); 1332 return true; 1333 } 1334 1335 void nmethod::flush() { 1336 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1337 // Note that there are no valid oops in the nmethod anymore. 1338 assert(!is_osr_method() || is_unloaded() || is_zombie(), 1339 "osr nmethod must be unloaded or zombie before flushing"); 1340 assert(is_zombie() || is_osr_method(), "must be a zombie method"); 1341 assert (!is_locked_by_vm(), "locked methods shouldn't be flushed"); 1342 assert_locked_or_safepoint(CodeCache_lock); 1343 1344 // completely deallocate this method 1345 Events::log(JavaThread::current(), "flushing nmethod " INTPTR_FORMAT, p2i(this)); 1346 if (PrintMethodFlushing) { 1347 tty->print_cr("*flushing %s nmethod %3d/" INTPTR_FORMAT ". Live blobs:" UINT32_FORMAT 1348 "/Free CodeCache:" SIZE_FORMAT "Kb", 1349 is_osr_method() ? "osr" : "",_compile_id, p2i(this), CodeCache::blob_count(), 1350 CodeCache::unallocated_capacity(CodeCache::get_code_blob_type(this))/1024); 1351 } 1352 1353 // We need to deallocate any ExceptionCache data. 1354 // Note that we do not need to grab the nmethod lock for this, it 1355 // better be thread safe if we're disposing of it! 1356 ExceptionCache* ec = exception_cache(); 1357 set_exception_cache(NULL); 1358 while(ec != NULL) { 1359 ExceptionCache* next = ec->next(); 1360 delete ec; 1361 ec = next; 1362 } 1363 1364 if (on_scavenge_root_list()) { 1365 CodeCache::drop_scavenge_root_nmethod(this); 1366 } 1367 1368 #if INCLUDE_JVMCI 1369 assert(_jvmci_installed_code == NULL, "should have been nulled out when transitioned to zombie"); 1370 assert(_speculation_log == NULL, "should have been nulled out when transitioned to zombie"); 1371 #endif 1372 1373 CodeBlob::flush(); 1374 CodeCache::free(this); 1375 } 1376 1377 oop nmethod::oop_at(int index) const { 1378 if (index == 0) { 1379 return NULL; 1380 } 1381 return NativeAccess<AS_NO_KEEPALIVE>::oop_load(oop_addr_at(index)); 1382 } 1383 1384 // 1385 // Notify all classes this nmethod is dependent on that it is no 1386 // longer dependent. This should only be called in two situations. 1387 // First, when a nmethod transitions to a zombie all dependents need 1388 // to be clear. Since zombification happens at a safepoint there's no 1389 // synchronization issues. The second place is a little more tricky. 1390 // During phase 1 of mark sweep class unloading may happen and as a 1391 // result some nmethods may get unloaded. In this case the flushing 1392 // of dependencies must happen during phase 1 since after GC any 1393 // dependencies in the unloaded nmethod won't be updated, so 1394 // traversing the dependency information in unsafe. In that case this 1395 // function is called with a boolean argument and this function only 1396 // notifies instanceKlasses that are reachable 1397 1398 void nmethod::flush_dependencies(bool delete_immediately) { 1399 DEBUG_ONLY(bool called_by_gc = Universe::heap()->is_gc_active() || Thread::current()->is_ConcurrentGC_thread();) 1400 assert(called_by_gc != delete_immediately, 1401 "delete_immediately is false if and only if we are called during GC"); 1402 if (!has_flushed_dependencies()) { 1403 set_has_flushed_dependencies(); 1404 for (Dependencies::DepStream deps(this); deps.next(); ) { 1405 if (deps.type() == Dependencies::call_site_target_value) { 1406 // CallSite dependencies are managed on per-CallSite instance basis. 1407 oop call_site = deps.argument_oop(0); 1408 if (delete_immediately) { 1409 assert_locked_or_safepoint(CodeCache_lock); 1410 MethodHandles::remove_dependent_nmethod(call_site, this); 1411 } else { 1412 MethodHandles::clean_dependency_context(call_site); 1413 } 1414 } else { 1415 Klass* klass = deps.context_type(); 1416 if (klass == NULL) { 1417 continue; // ignore things like evol_method 1418 } 1419 // During GC delete_immediately is false, and liveness 1420 // of dependee determines class that needs to be updated. 1421 if (delete_immediately) { 1422 assert_locked_or_safepoint(CodeCache_lock); 1423 InstanceKlass::cast(klass)->remove_dependent_nmethod(this); 1424 } else if (klass->is_loader_alive()) { 1425 // The GC may clean dependency contexts concurrently and in parallel. 1426 InstanceKlass::cast(klass)->clean_dependency_context(); 1427 } 1428 } 1429 } 1430 } 1431 } 1432 1433 // ------------------------------------------------------------------ 1434 // post_compiled_method_load_event 1435 // new method for install_code() path 1436 // Transfer information from compilation to jvmti 1437 void nmethod::post_compiled_method_load_event() { 1438 1439 Method* moop = method(); 1440 HOTSPOT_COMPILED_METHOD_LOAD( 1441 (char *) moop->klass_name()->bytes(), 1442 moop->klass_name()->utf8_length(), 1443 (char *) moop->name()->bytes(), 1444 moop->name()->utf8_length(), 1445 (char *) moop->signature()->bytes(), 1446 moop->signature()->utf8_length(), 1447 insts_begin(), insts_size()); 1448 1449 if (JvmtiExport::should_post_compiled_method_load() || 1450 JvmtiExport::should_post_compiled_method_unload()) { 1451 get_and_cache_jmethod_id(); 1452 } 1453 1454 if (JvmtiExport::should_post_compiled_method_load()) { 1455 // Let the Service thread (which is a real Java thread) post the event 1456 MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag); 1457 JvmtiDeferredEventQueue::enqueue( 1458 JvmtiDeferredEvent::compiled_method_load_event(this)); 1459 } 1460 } 1461 1462 jmethodID nmethod::get_and_cache_jmethod_id() { 1463 if (_jmethod_id == NULL) { 1464 // Cache the jmethod_id since it can no longer be looked up once the 1465 // method itself has been marked for unloading. 1466 _jmethod_id = method()->jmethod_id(); 1467 } 1468 return _jmethod_id; 1469 } 1470 1471 void nmethod::post_compiled_method_unload() { 1472 if (unload_reported()) { 1473 // During unloading we transition to unloaded and then to zombie 1474 // and the unloading is reported during the first transition. 1475 return; 1476 } 1477 1478 assert(_method != NULL && !is_unloaded(), "just checking"); 1479 DTRACE_METHOD_UNLOAD_PROBE(method()); 1480 1481 // If a JVMTI agent has enabled the CompiledMethodUnload event then 1482 // post the event. Sometime later this nmethod will be made a zombie 1483 // by the sweeper but the Method* will not be valid at that point. 1484 // If the _jmethod_id is null then no load event was ever requested 1485 // so don't bother posting the unload. The main reason for this is 1486 // that the jmethodID is a weak reference to the Method* so if 1487 // it's being unloaded there's no way to look it up since the weak 1488 // ref will have been cleared. 1489 if (_jmethod_id != NULL && JvmtiExport::should_post_compiled_method_unload()) { 1490 assert(!unload_reported(), "already unloaded"); 1491 JvmtiDeferredEvent event = 1492 JvmtiDeferredEvent::compiled_method_unload_event(this, 1493 _jmethod_id, insts_begin()); 1494 MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag); 1495 JvmtiDeferredEventQueue::enqueue(event); 1496 } 1497 1498 // The JVMTI CompiledMethodUnload event can be enabled or disabled at 1499 // any time. As the nmethod is being unloaded now we mark it has 1500 // having the unload event reported - this will ensure that we don't 1501 // attempt to report the event in the unlikely scenario where the 1502 // event is enabled at the time the nmethod is made a zombie. 1503 set_unload_reported(); 1504 } 1505 1506 // Iterate over metadata calling this function. Used by RedefineClasses 1507 void nmethod::metadata_do(void f(Metadata*)) { 1508 { 1509 // Visit all immediate references that are embedded in the instruction stream. 1510 RelocIterator iter(this, oops_reloc_begin()); 1511 while (iter.next()) { 1512 if (iter.type() == relocInfo::metadata_type ) { 1513 metadata_Relocation* r = iter.metadata_reloc(); 1514 // In this metadata, we must only follow those metadatas directly embedded in 1515 // the code. Other metadatas (oop_index>0) are seen as part of 1516 // the metadata section below. 1517 assert(1 == (r->metadata_is_immediate()) + 1518 (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()), 1519 "metadata must be found in exactly one place"); 1520 if (r->metadata_is_immediate() && r->metadata_value() != NULL) { 1521 Metadata* md = r->metadata_value(); 1522 if (md != _method) f(md); 1523 } 1524 } else if (iter.type() == relocInfo::virtual_call_type) { 1525 // Check compiledIC holders associated with this nmethod 1526 ResourceMark rm; 1527 CompiledIC *ic = CompiledIC_at(&iter); 1528 if (ic->is_icholder_call()) { 1529 CompiledICHolder* cichk = ic->cached_icholder(); 1530 f(cichk->holder_metadata()); 1531 f(cichk->holder_klass()); 1532 } else { 1533 Metadata* ic_oop = ic->cached_metadata(); 1534 if (ic_oop != NULL) { 1535 f(ic_oop); 1536 } 1537 } 1538 } 1539 } 1540 } 1541 1542 // Visit the metadata section 1543 for (Metadata** p = metadata_begin(); p < metadata_end(); p++) { 1544 if (*p == Universe::non_oop_word() || *p == NULL) continue; // skip non-oops 1545 Metadata* md = *p; 1546 f(md); 1547 } 1548 1549 // Visit metadata not embedded in the other places. 1550 if (_method != NULL) f(_method); 1551 } 1552 1553 // The _is_unloading_state encodes a tuple comprising the unloading cycle 1554 // and the result of IsUnloadingBehaviour::is_unloading() fpr that cycle. 1555 // This is the bit layout of the _is_unloading_state byte: 00000CCU 1556 // CC refers to the cycle, which has 2 bits, and U refers to the result of 1557 // IsUnloadingBehaviour::is_unloading() for that unloading cycle. 1558 1559 class IsUnloadingState: public AllStatic { 1560 static const uint8_t _is_unloading_mask = 1; 1561 static const uint8_t _is_unloading_shift = 0; 1562 static const uint8_t _unloading_cycle_mask = 6; 1563 static const uint8_t _unloading_cycle_shift = 1; 1564 1565 static uint8_t set_is_unloading(uint8_t state, bool value) { 1566 state &= ~_is_unloading_mask; 1567 if (value) { 1568 state |= 1 << _is_unloading_shift; 1569 } 1570 assert(is_unloading(state) == value, "unexpected unloading cycle overflow"); 1571 return state; 1572 } 1573 1574 static uint8_t set_unloading_cycle(uint8_t state, uint8_t value) { 1575 state &= ~_unloading_cycle_mask; 1576 state |= value << _unloading_cycle_shift; 1577 assert(unloading_cycle(state) == value, "unexpected unloading cycle overflow"); 1578 return state; 1579 } 1580 1581 public: 1582 static bool is_unloading(uint8_t state) { return (state & _is_unloading_mask) >> _is_unloading_shift == 1; } 1583 static uint8_t unloading_cycle(uint8_t state) { return (state & _unloading_cycle_mask) >> _unloading_cycle_shift; } 1584 1585 static uint8_t create(bool is_unloading, uint8_t unloading_cycle) { 1586 uint8_t state = 0; 1587 state = set_is_unloading(state, is_unloading); 1588 state = set_unloading_cycle(state, unloading_cycle); 1589 return state; 1590 } 1591 }; 1592 1593 bool nmethod::is_unloading() { 1594 uint8_t state = RawAccess<MO_RELAXED>::load(&_is_unloading_state); 1595 bool state_is_unloading = IsUnloadingState::is_unloading(state); 1596 uint8_t state_unloading_cycle = IsUnloadingState::unloading_cycle(state); 1597 if (state_is_unloading) { 1598 return true; 1599 } 1600 uint8_t current_cycle = CodeCache::unloading_cycle(); 1601 if (state_unloading_cycle == current_cycle) { 1602 return false; 1603 } 1604 1605 // The IsUnloadingBehaviour is responsible for checking if there are any dead 1606 // oops in the CompiledMethod, by calling oops_do on it. 1607 state_unloading_cycle = current_cycle; 1608 1609 if (is_zombie()) { 1610 // Zombies without calculated unloading epoch are never unloading due to GC. 1611 1612 // There are no races where a previously observed is_unloading() nmethod 1613 // suddenly becomes not is_unloading() due to here being observed as zombie. 1614 1615 // With STW unloading, all is_alive() && is_unloading() nmethods are unlinked 1616 // and unloaded in the safepoint. That makes races where an nmethod is first 1617 // observed as is_alive() && is_unloading() and subsequently observed as 1618 // is_zombie() impossible. 1619 1620 // With concurrent unloading, all references to is_unloading() nmethods are 1621 // first unlinked (e.g. IC caches and dependency contexts). Then a global 1622 // handshake operation is performed with all JavaThreads before finally 1623 // unloading the nmethods. The sweeper never converts is_alive() && is_unloading() 1624 // nmethods to zombies; it waits for them to become is_unloaded(). So before 1625 // the global handshake, it is impossible for is_unloading() nmethods to 1626 // racingly become is_zombie(). And is_unloading() is calculated for all is_alive() 1627 // nmethods before taking that global handshake, meaning that it will never 1628 // be recalculated after the handshake. 1629 1630 // After that global handshake, is_unloading() nmethods are only observable 1631 // to the iterators, and they will never trigger recomputation of the cached 1632 // is_unloading_state, and hence may not suffer from such races. 1633 1634 state_is_unloading = false; 1635 } else { 1636 state_is_unloading = IsUnloadingBehaviour::current()->is_unloading(this); 1637 } 1638 1639 state = IsUnloadingState::create(state_is_unloading, state_unloading_cycle); 1640 1641 RawAccess<MO_RELAXED>::store(&_is_unloading_state, state); 1642 1643 return state_is_unloading; 1644 } 1645 1646 void nmethod::clear_unloading_state() { 1647 uint8_t state = IsUnloadingState::create(false, CodeCache::unloading_cycle()); 1648 RawAccess<MO_RELAXED>::store(&_is_unloading_state, state); 1649 } 1650 1651 1652 // This is called at the end of the strong tracing/marking phase of a 1653 // GC to unload an nmethod if it contains otherwise unreachable 1654 // oops. 1655 1656 void nmethod::do_unloading(bool unloading_occurred) { 1657 // Make sure the oop's ready to receive visitors 1658 assert(!is_zombie() && !is_unloaded(), 1659 "should not call follow on zombie or unloaded nmethod"); 1660 1661 if (is_unloading()) { 1662 make_unloaded(); 1663 } else { 1664 #if INCLUDE_JVMCI 1665 if (_jvmci_installed_code != NULL) { 1666 if (JNIHandles::is_global_weak_cleared(_jvmci_installed_code)) { 1667 if (_jvmci_installed_code_triggers_invalidation) { 1668 make_not_entrant(); 1669 } 1670 clear_jvmci_installed_code(); 1671 } 1672 } 1673 #endif 1674 1675 guarantee(unload_nmethod_caches(unloading_occurred), 1676 "Should not need transition stubs"); 1677 } 1678 } 1679 1680 void nmethod::oops_do(OopClosure* f, bool allow_zombie) { 1681 // make sure the oops ready to receive visitors 1682 assert(allow_zombie || !is_zombie(), "should not call follow on zombie nmethod"); 1683 assert(!is_unloaded(), "should not call follow on unloaded nmethod"); 1684 1685 // Prevent extra code cache walk for platforms that don't have immediate oops. 1686 if (relocInfo::mustIterateImmediateOopsInCode()) { 1687 RelocIterator iter(this, oops_reloc_begin()); 1688 1689 while (iter.next()) { 1690 if (iter.type() == relocInfo::oop_type ) { 1691 oop_Relocation* r = iter.oop_reloc(); 1692 // In this loop, we must only follow those oops directly embedded in 1693 // the code. Other oops (oop_index>0) are seen as part of scopes_oops. 1694 assert(1 == (r->oop_is_immediate()) + 1695 (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()), 1696 "oop must be found in exactly one place"); 1697 if (r->oop_is_immediate() && r->oop_value() != NULL) { 1698 f->do_oop(r->oop_addr()); 1699 } 1700 } 1701 } 1702 } 1703 1704 // Scopes 1705 // This includes oop constants not inlined in the code stream. 1706 for (oop* p = oops_begin(); p < oops_end(); p++) { 1707 if (*p == Universe::non_oop_word()) continue; // skip non-oops 1708 f->do_oop(p); 1709 } 1710 } 1711 1712 #define NMETHOD_SENTINEL ((nmethod*)badAddress) 1713 1714 nmethod* volatile nmethod::_oops_do_mark_nmethods; 1715 1716 // An nmethod is "marked" if its _mark_link is set non-null. 1717 // Even if it is the end of the linked list, it will have a non-null link value, 1718 // as long as it is on the list. 1719 // This code must be MP safe, because it is used from parallel GC passes. 1720 bool nmethod::test_set_oops_do_mark() { 1721 assert(nmethod::oops_do_marking_is_active(), "oops_do_marking_prologue must be called"); 1722 if (_oops_do_mark_link == NULL) { 1723 // Claim this nmethod for this thread to mark. 1724 if (Atomic::replace_if_null(NMETHOD_SENTINEL, &_oops_do_mark_link)) { 1725 // Atomically append this nmethod (now claimed) to the head of the list: 1726 nmethod* observed_mark_nmethods = _oops_do_mark_nmethods; 1727 for (;;) { 1728 nmethod* required_mark_nmethods = observed_mark_nmethods; 1729 _oops_do_mark_link = required_mark_nmethods; 1730 observed_mark_nmethods = 1731 Atomic::cmpxchg(this, &_oops_do_mark_nmethods, required_mark_nmethods); 1732 if (observed_mark_nmethods == required_mark_nmethods) 1733 break; 1734 } 1735 // Mark was clear when we first saw this guy. 1736 LogTarget(Trace, gc, nmethod) lt; 1737 if (lt.is_enabled()) { 1738 LogStream ls(lt); 1739 CompileTask::print(&ls, this, "oops_do, mark", /*short_form:*/ true); 1740 } 1741 return false; 1742 } 1743 } 1744 // On fall through, another racing thread marked this nmethod before we did. 1745 return true; 1746 } 1747 1748 void nmethod::oops_do_marking_prologue() { 1749 log_trace(gc, nmethod)("oops_do_marking_prologue"); 1750 assert(_oops_do_mark_nmethods == NULL, "must not call oops_do_marking_prologue twice in a row"); 1751 // We use cmpxchg instead of regular assignment here because the user 1752 // may fork a bunch of threads, and we need them all to see the same state. 1753 nmethod* observed = Atomic::cmpxchg(NMETHOD_SENTINEL, &_oops_do_mark_nmethods, (nmethod*)NULL); 1754 guarantee(observed == NULL, "no races in this sequential code"); 1755 } 1756 1757 void nmethod::oops_do_marking_epilogue() { 1758 assert(_oops_do_mark_nmethods != NULL, "must not call oops_do_marking_epilogue twice in a row"); 1759 nmethod* cur = _oops_do_mark_nmethods; 1760 while (cur != NMETHOD_SENTINEL) { 1761 assert(cur != NULL, "not NULL-terminated"); 1762 nmethod* next = cur->_oops_do_mark_link; 1763 cur->_oops_do_mark_link = NULL; 1764 DEBUG_ONLY(cur->verify_oop_relocations()); 1765 1766 LogTarget(Trace, gc, nmethod) lt; 1767 if (lt.is_enabled()) { 1768 LogStream ls(lt); 1769 CompileTask::print(&ls, cur, "oops_do, unmark", /*short_form:*/ true); 1770 } 1771 cur = next; 1772 } 1773 nmethod* required = _oops_do_mark_nmethods; 1774 nmethod* observed = Atomic::cmpxchg((nmethod*)NULL, &_oops_do_mark_nmethods, required); 1775 guarantee(observed == required, "no races in this sequential code"); 1776 log_trace(gc, nmethod)("oops_do_marking_epilogue"); 1777 } 1778 1779 class DetectScavengeRoot: public OopClosure { 1780 bool _detected_scavenge_root; 1781 nmethod* _print_nm; 1782 public: 1783 DetectScavengeRoot(nmethod* nm) : _detected_scavenge_root(false), _print_nm(nm) {} 1784 1785 bool detected_scavenge_root() { return _detected_scavenge_root; } 1786 virtual void do_oop(oop* p) { 1787 if ((*p) != NULL && Universe::heap()->is_scavengable(*p)) { 1788 NOT_PRODUCT(maybe_print(p)); 1789 _detected_scavenge_root = true; 1790 } 1791 } 1792 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); } 1793 1794 #ifndef PRODUCT 1795 void maybe_print(oop* p) { 1796 LogTarget(Trace, gc, nmethod) lt; 1797 if (lt.is_enabled()) { 1798 LogStream ls(lt); 1799 if (!_detected_scavenge_root) { 1800 CompileTask::print(&ls, _print_nm, "new scavenge root", /*short_form:*/ true); 1801 } 1802 ls.print("" PTR_FORMAT "[offset=%d] detected scavengable oop " PTR_FORMAT " (found at " PTR_FORMAT ") ", 1803 p2i(_print_nm), (int)((intptr_t)p - (intptr_t)_print_nm), 1804 p2i(*p), p2i(p)); 1805 ls.cr(); 1806 } 1807 } 1808 #endif //PRODUCT 1809 }; 1810 1811 bool nmethod::detect_scavenge_root_oops() { 1812 DetectScavengeRoot detect_scavenge_root(this); 1813 oops_do(&detect_scavenge_root); 1814 return detect_scavenge_root.detected_scavenge_root(); 1815 } 1816 1817 inline bool includes(void* p, void* from, void* to) { 1818 return from <= p && p < to; 1819 } 1820 1821 1822 void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) { 1823 assert(count >= 2, "must be sentinel values, at least"); 1824 1825 #ifdef ASSERT 1826 // must be sorted and unique; we do a binary search in find_pc_desc() 1827 int prev_offset = pcs[0].pc_offset(); 1828 assert(prev_offset == PcDesc::lower_offset_limit, 1829 "must start with a sentinel"); 1830 for (int i = 1; i < count; i++) { 1831 int this_offset = pcs[i].pc_offset(); 1832 assert(this_offset > prev_offset, "offsets must be sorted"); 1833 prev_offset = this_offset; 1834 } 1835 assert(prev_offset == PcDesc::upper_offset_limit, 1836 "must end with a sentinel"); 1837 #endif //ASSERT 1838 1839 // Search for MethodHandle invokes and tag the nmethod. 1840 for (int i = 0; i < count; i++) { 1841 if (pcs[i].is_method_handle_invoke()) { 1842 set_has_method_handle_invokes(true); 1843 break; 1844 } 1845 } 1846 assert(has_method_handle_invokes() == (_deopt_mh_handler_begin != NULL), "must have deopt mh handler"); 1847 1848 int size = count * sizeof(PcDesc); 1849 assert(scopes_pcs_size() >= size, "oob"); 1850 memcpy(scopes_pcs_begin(), pcs, size); 1851 1852 // Adjust the final sentinel downward. 1853 PcDesc* last_pc = &scopes_pcs_begin()[count-1]; 1854 assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity"); 1855 last_pc->set_pc_offset(content_size() + 1); 1856 for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) { 1857 // Fill any rounding gaps with copies of the last record. 1858 last_pc[1] = last_pc[0]; 1859 } 1860 // The following assert could fail if sizeof(PcDesc) is not 1861 // an integral multiple of oopSize (the rounding term). 1862 // If it fails, change the logic to always allocate a multiple 1863 // of sizeof(PcDesc), and fill unused words with copies of *last_pc. 1864 assert(last_pc + 1 == scopes_pcs_end(), "must match exactly"); 1865 } 1866 1867 void nmethod::copy_scopes_data(u_char* buffer, int size) { 1868 assert(scopes_data_size() >= size, "oob"); 1869 memcpy(scopes_data_begin(), buffer, size); 1870 } 1871 1872 #ifdef ASSERT 1873 static PcDesc* linear_search(const PcDescSearch& search, int pc_offset, bool approximate) { 1874 PcDesc* lower = search.scopes_pcs_begin(); 1875 PcDesc* upper = search.scopes_pcs_end(); 1876 lower += 1; // exclude initial sentinel 1877 PcDesc* res = NULL; 1878 for (PcDesc* p = lower; p < upper; p++) { 1879 NOT_PRODUCT(--pc_nmethod_stats.pc_desc_tests); // don't count this call to match_desc 1880 if (match_desc(p, pc_offset, approximate)) { 1881 if (res == NULL) 1882 res = p; 1883 else 1884 res = (PcDesc*) badAddress; 1885 } 1886 } 1887 return res; 1888 } 1889 #endif 1890 1891 1892 // Finds a PcDesc with real-pc equal to "pc" 1893 PcDesc* PcDescContainer::find_pc_desc_internal(address pc, bool approximate, const PcDescSearch& search) { 1894 address base_address = search.code_begin(); 1895 if ((pc < base_address) || 1896 (pc - base_address) >= (ptrdiff_t) PcDesc::upper_offset_limit) { 1897 return NULL; // PC is wildly out of range 1898 } 1899 int pc_offset = (int) (pc - base_address); 1900 1901 // Check the PcDesc cache if it contains the desired PcDesc 1902 // (This as an almost 100% hit rate.) 1903 PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate); 1904 if (res != NULL) { 1905 assert(res == linear_search(search, pc_offset, approximate), "cache ok"); 1906 return res; 1907 } 1908 1909 // Fallback algorithm: quasi-linear search for the PcDesc 1910 // Find the last pc_offset less than the given offset. 1911 // The successor must be the required match, if there is a match at all. 1912 // (Use a fixed radix to avoid expensive affine pointer arithmetic.) 1913 PcDesc* lower = search.scopes_pcs_begin(); 1914 PcDesc* upper = search.scopes_pcs_end(); 1915 upper -= 1; // exclude final sentinel 1916 if (lower >= upper) return NULL; // native method; no PcDescs at all 1917 1918 #define assert_LU_OK \ 1919 /* invariant on lower..upper during the following search: */ \ 1920 assert(lower->pc_offset() < pc_offset, "sanity"); \ 1921 assert(upper->pc_offset() >= pc_offset, "sanity") 1922 assert_LU_OK; 1923 1924 // Use the last successful return as a split point. 1925 PcDesc* mid = _pc_desc_cache.last_pc_desc(); 1926 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches); 1927 if (mid->pc_offset() < pc_offset) { 1928 lower = mid; 1929 } else { 1930 upper = mid; 1931 } 1932 1933 // Take giant steps at first (4096, then 256, then 16, then 1) 1934 const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ debug_only(-1); 1935 const int RADIX = (1 << LOG2_RADIX); 1936 for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) { 1937 while ((mid = lower + step) < upper) { 1938 assert_LU_OK; 1939 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches); 1940 if (mid->pc_offset() < pc_offset) { 1941 lower = mid; 1942 } else { 1943 upper = mid; 1944 break; 1945 } 1946 } 1947 assert_LU_OK; 1948 } 1949 1950 // Sneak up on the value with a linear search of length ~16. 1951 while (true) { 1952 assert_LU_OK; 1953 mid = lower + 1; 1954 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches); 1955 if (mid->pc_offset() < pc_offset) { 1956 lower = mid; 1957 } else { 1958 upper = mid; 1959 break; 1960 } 1961 } 1962 #undef assert_LU_OK 1963 1964 if (match_desc(upper, pc_offset, approximate)) { 1965 assert(upper == linear_search(search, pc_offset, approximate), "search ok"); 1966 _pc_desc_cache.add_pc_desc(upper); 1967 return upper; 1968 } else { 1969 assert(NULL == linear_search(search, pc_offset, approximate), "search ok"); 1970 return NULL; 1971 } 1972 } 1973 1974 1975 void nmethod::check_all_dependencies(DepChange& changes) { 1976 // Checked dependencies are allocated into this ResourceMark 1977 ResourceMark rm; 1978 1979 // Turn off dependency tracing while actually testing dependencies. 1980 NOT_PRODUCT( FlagSetting fs(TraceDependencies, false) ); 1981 1982 typedef ResourceHashtable<DependencySignature, int, &DependencySignature::hash, 1983 &DependencySignature::equals, 11027> DepTable; 1984 1985 DepTable* table = new DepTable(); 1986 1987 // Iterate over live nmethods and check dependencies of all nmethods that are not 1988 // marked for deoptimization. A particular dependency is only checked once. 1989 NMethodIterator iter(NMethodIterator::only_alive_and_not_unloading); 1990 while(iter.next()) { 1991 nmethod* nm = iter.method(); 1992 // Only notify for live nmethods 1993 if (!nm->is_marked_for_deoptimization()) { 1994 for (Dependencies::DepStream deps(nm); deps.next(); ) { 1995 // Construct abstraction of a dependency. 1996 DependencySignature* current_sig = new DependencySignature(deps); 1997 1998 // Determine if dependency is already checked. table->put(...) returns 1999 // 'true' if the dependency is added (i.e., was not in the hashtable). 2000 if (table->put(*current_sig, 1)) { 2001 if (deps.check_dependency() != NULL) { 2002 // Dependency checking failed. Print out information about the failed 2003 // dependency and finally fail with an assert. We can fail here, since 2004 // dependency checking is never done in a product build. 2005 tty->print_cr("Failed dependency:"); 2006 changes.print(); 2007 nm->print(); 2008 nm->print_dependencies(); 2009 assert(false, "Should have been marked for deoptimization"); 2010 } 2011 } 2012 } 2013 } 2014 } 2015 } 2016 2017 bool nmethod::check_dependency_on(DepChange& changes) { 2018 // What has happened: 2019 // 1) a new class dependee has been added 2020 // 2) dependee and all its super classes have been marked 2021 bool found_check = false; // set true if we are upset 2022 for (Dependencies::DepStream deps(this); deps.next(); ) { 2023 // Evaluate only relevant dependencies. 2024 if (deps.spot_check_dependency_at(changes) != NULL) { 2025 found_check = true; 2026 NOT_DEBUG(break); 2027 } 2028 } 2029 return found_check; 2030 } 2031 2032 bool nmethod::is_evol_dependent() { 2033 for (Dependencies::DepStream deps(this); deps.next(); ) { 2034 if (deps.type() == Dependencies::evol_method) { 2035 Method* method = deps.method_argument(0); 2036 if (method->is_old()) { 2037 if (log_is_enabled(Debug, redefine, class, nmethod)) { 2038 ResourceMark rm; 2039 log_debug(redefine, class, nmethod) 2040 ("Found evol dependency of nmethod %s.%s(%s) compile_id=%d on method %s.%s(%s)", 2041 _method->method_holder()->external_name(), 2042 _method->name()->as_C_string(), 2043 _method->signature()->as_C_string(), 2044 compile_id(), 2045 method->method_holder()->external_name(), 2046 method->name()->as_C_string(), 2047 method->signature()->as_C_string()); 2048 } 2049 if (TraceDependencies || LogCompilation) 2050 deps.log_dependency(method->method_holder()); 2051 return true; 2052 } 2053 } 2054 } 2055 return false; 2056 } 2057 2058 // Called from mark_for_deoptimization, when dependee is invalidated. 2059 bool nmethod::is_dependent_on_method(Method* dependee) { 2060 for (Dependencies::DepStream deps(this); deps.next(); ) { 2061 if (deps.type() != Dependencies::evol_method) 2062 continue; 2063 Method* method = deps.method_argument(0); 2064 if (method == dependee) return true; 2065 } 2066 return false; 2067 } 2068 2069 2070 bool nmethod::is_patchable_at(address instr_addr) { 2071 assert(insts_contains(instr_addr), "wrong nmethod used"); 2072 if (is_zombie()) { 2073 // a zombie may never be patched 2074 return false; 2075 } 2076 return true; 2077 } 2078 2079 2080 address nmethod::continuation_for_implicit_exception(address pc) { 2081 // Exception happened outside inline-cache check code => we are inside 2082 // an active nmethod => use cpc to determine a return address 2083 int exception_offset = pc - code_begin(); 2084 int cont_offset = ImplicitExceptionTable(this).at( exception_offset ); 2085 #ifdef ASSERT 2086 if (cont_offset == 0) { 2087 Thread* thread = Thread::current(); 2088 ResetNoHandleMark rnm; // Might be called from LEAF/QUICK ENTRY 2089 HandleMark hm(thread); 2090 ResourceMark rm(thread); 2091 CodeBlob* cb = CodeCache::find_blob(pc); 2092 assert(cb != NULL && cb == this, ""); 2093 ttyLocker ttyl; 2094 tty->print_cr("implicit exception happened at " INTPTR_FORMAT, p2i(pc)); 2095 print(); 2096 method()->print_codes(); 2097 print_code(); 2098 print_pcs(); 2099 } 2100 #endif 2101 if (cont_offset == 0) { 2102 // Let the normal error handling report the exception 2103 return NULL; 2104 } 2105 return code_begin() + cont_offset; 2106 } 2107 2108 2109 2110 void nmethod_init() { 2111 // make sure you didn't forget to adjust the filler fields 2112 assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word"); 2113 } 2114 2115 2116 //------------------------------------------------------------------------------------------- 2117 2118 2119 // QQQ might we make this work from a frame?? 2120 nmethodLocker::nmethodLocker(address pc) { 2121 CodeBlob* cb = CodeCache::find_blob(pc); 2122 guarantee(cb != NULL && cb->is_compiled(), "bad pc for a nmethod found"); 2123 _nm = cb->as_compiled_method(); 2124 lock_nmethod(_nm); 2125 } 2126 2127 // Only JvmtiDeferredEvent::compiled_method_unload_event() 2128 // should pass zombie_ok == true. 2129 void nmethodLocker::lock_nmethod(CompiledMethod* cm, bool zombie_ok) { 2130 if (cm == NULL) return; 2131 if (cm->is_aot()) return; // FIXME: Revisit once _lock_count is added to aot_method 2132 nmethod* nm = cm->as_nmethod(); 2133 Atomic::inc(&nm->_lock_count); 2134 assert(zombie_ok || !nm->is_zombie(), "cannot lock a zombie method"); 2135 } 2136 2137 void nmethodLocker::unlock_nmethod(CompiledMethod* cm) { 2138 if (cm == NULL) return; 2139 if (cm->is_aot()) return; // FIXME: Revisit once _lock_count is added to aot_method 2140 nmethod* nm = cm->as_nmethod(); 2141 Atomic::dec(&nm->_lock_count); 2142 assert(nm->_lock_count >= 0, "unmatched nmethod lock/unlock"); 2143 } 2144 2145 2146 // ----------------------------------------------------------------------------- 2147 // Verification 2148 2149 class VerifyOopsClosure: public OopClosure { 2150 nmethod* _nm; 2151 bool _ok; 2152 public: 2153 VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { } 2154 bool ok() { return _ok; } 2155 virtual void do_oop(oop* p) { 2156 if (oopDesc::is_oop_or_null(*p)) return; 2157 if (_ok) { 2158 _nm->print_nmethod(true); 2159 _ok = false; 2160 } 2161 tty->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)", 2162 p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm)); 2163 } 2164 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); } 2165 }; 2166 2167 void nmethod::verify() { 2168 2169 // Hmm. OSR methods can be deopted but not marked as zombie or not_entrant 2170 // seems odd. 2171 2172 if (is_zombie() || is_not_entrant() || is_unloaded()) 2173 return; 2174 2175 // Make sure all the entry points are correctly aligned for patching. 2176 NativeJump::check_verified_entry_alignment(entry_point(), verified_entry_point()); 2177 2178 // assert(oopDesc::is_oop(method()), "must be valid"); 2179 2180 ResourceMark rm; 2181 2182 if (!CodeCache::contains(this)) { 2183 fatal("nmethod at " INTPTR_FORMAT " not in zone", p2i(this)); 2184 } 2185 2186 if(is_native_method() ) 2187 return; 2188 2189 nmethod* nm = CodeCache::find_nmethod(verified_entry_point()); 2190 if (nm != this) { 2191 fatal("findNMethod did not find this nmethod (" INTPTR_FORMAT ")", p2i(this)); 2192 } 2193 2194 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) { 2195 if (! p->verify(this)) { 2196 tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", p2i(this)); 2197 } 2198 } 2199 2200 VerifyOopsClosure voc(this); 2201 oops_do(&voc); 2202 assert(voc.ok(), "embedded oops must be OK"); 2203 Universe::heap()->verify_nmethod(this); 2204 2205 verify_scopes(); 2206 } 2207 2208 2209 void nmethod::verify_interrupt_point(address call_site) { 2210 // Verify IC only when nmethod installation is finished. 2211 if (!is_not_installed()) { 2212 if (CompiledICLocker::is_safe(this)) { 2213 CompiledIC_at(this, call_site); 2214 CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops()); 2215 } else { 2216 CompiledICLocker ml_verify(this); 2217 CompiledIC_at(this, call_site); 2218 } 2219 } 2220 2221 PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address()); 2222 assert(pd != NULL, "PcDesc must exist"); 2223 for (ScopeDesc* sd = new ScopeDesc(this, pd->scope_decode_offset(), 2224 pd->obj_decode_offset(), pd->should_reexecute(), pd->rethrow_exception(), 2225 pd->return_oop()); 2226 !sd->is_top(); sd = sd->sender()) { 2227 sd->verify(); 2228 } 2229 } 2230 2231 void nmethod::verify_scopes() { 2232 if( !method() ) return; // Runtime stubs have no scope 2233 if (method()->is_native()) return; // Ignore stub methods. 2234 // iterate through all interrupt point 2235 // and verify the debug information is valid. 2236 RelocIterator iter((nmethod*)this); 2237 while (iter.next()) { 2238 address stub = NULL; 2239 switch (iter.type()) { 2240 case relocInfo::virtual_call_type: 2241 verify_interrupt_point(iter.addr()); 2242 break; 2243 case relocInfo::opt_virtual_call_type: 2244 stub = iter.opt_virtual_call_reloc()->static_stub(false); 2245 verify_interrupt_point(iter.addr()); 2246 break; 2247 case relocInfo::static_call_type: 2248 stub = iter.static_call_reloc()->static_stub(false); 2249 //verify_interrupt_point(iter.addr()); 2250 break; 2251 case relocInfo::runtime_call_type: 2252 case relocInfo::runtime_call_w_cp_type: { 2253 address destination = iter.reloc()->value(); 2254 // Right now there is no way to find out which entries support 2255 // an interrupt point. It would be nice if we had this 2256 // information in a table. 2257 break; 2258 } 2259 default: 2260 break; 2261 } 2262 assert(stub == NULL || stub_contains(stub), "static call stub outside stub section"); 2263 } 2264 } 2265 2266 2267 // ----------------------------------------------------------------------------- 2268 // Non-product code 2269 #ifndef PRODUCT 2270 2271 class DebugScavengeRoot: public OopClosure { 2272 nmethod* _nm; 2273 bool _ok; 2274 public: 2275 DebugScavengeRoot(nmethod* nm) : _nm(nm), _ok(true) { } 2276 bool ok() { return _ok; } 2277 virtual void do_oop(oop* p) { 2278 if ((*p) == NULL || !Universe::heap()->is_scavengable(*p)) return; 2279 if (_ok) { 2280 _nm->print_nmethod(true); 2281 _ok = false; 2282 } 2283 tty->print_cr("*** scavengable oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)", 2284 p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm)); 2285 (*p)->print(); 2286 } 2287 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); } 2288 }; 2289 2290 void nmethod::verify_scavenge_root_oops() { 2291 if (!on_scavenge_root_list()) { 2292 // Actually look inside, to verify the claim that it's clean. 2293 DebugScavengeRoot debug_scavenge_root(this); 2294 oops_do(&debug_scavenge_root); 2295 if (!debug_scavenge_root.ok()) 2296 fatal("found an unadvertised bad scavengable oop in the code cache"); 2297 } 2298 assert(scavenge_root_not_marked(), ""); 2299 } 2300 2301 #endif // PRODUCT 2302 2303 // Printing operations 2304 2305 void nmethod::print() const { 2306 ResourceMark rm; 2307 ttyLocker ttyl; // keep the following output all in one block 2308 2309 tty->print("Compiled method "); 2310 2311 if (is_compiled_by_c1()) { 2312 tty->print("(c1) "); 2313 } else if (is_compiled_by_c2()) { 2314 tty->print("(c2) "); 2315 } else if (is_compiled_by_jvmci()) { 2316 tty->print("(JVMCI) "); 2317 } else { 2318 tty->print("(nm) "); 2319 } 2320 2321 print_on(tty, NULL); 2322 2323 if (WizardMode) { 2324 tty->print("((nmethod*) " INTPTR_FORMAT ") ", p2i(this)); 2325 tty->print(" for method " INTPTR_FORMAT , p2i(method())); 2326 tty->print(" { "); 2327 tty->print_cr("%s ", state()); 2328 if (on_scavenge_root_list()) tty->print("scavenge_root "); 2329 tty->print_cr("}:"); 2330 } 2331 if (size () > 0) tty->print_cr(" total in heap [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2332 p2i(this), 2333 p2i(this) + size(), 2334 size()); 2335 if (relocation_size () > 0) tty->print_cr(" relocation [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2336 p2i(relocation_begin()), 2337 p2i(relocation_end()), 2338 relocation_size()); 2339 if (consts_size () > 0) tty->print_cr(" constants [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2340 p2i(consts_begin()), 2341 p2i(consts_end()), 2342 consts_size()); 2343 if (insts_size () > 0) tty->print_cr(" main code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2344 p2i(insts_begin()), 2345 p2i(insts_end()), 2346 insts_size()); 2347 if (stub_size () > 0) tty->print_cr(" stub code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2348 p2i(stub_begin()), 2349 p2i(stub_end()), 2350 stub_size()); 2351 if (oops_size () > 0) tty->print_cr(" oops [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2352 p2i(oops_begin()), 2353 p2i(oops_end()), 2354 oops_size()); 2355 if (metadata_size () > 0) tty->print_cr(" metadata [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2356 p2i(metadata_begin()), 2357 p2i(metadata_end()), 2358 metadata_size()); 2359 if (scopes_data_size () > 0) tty->print_cr(" scopes data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2360 p2i(scopes_data_begin()), 2361 p2i(scopes_data_end()), 2362 scopes_data_size()); 2363 if (scopes_pcs_size () > 0) tty->print_cr(" scopes pcs [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2364 p2i(scopes_pcs_begin()), 2365 p2i(scopes_pcs_end()), 2366 scopes_pcs_size()); 2367 if (dependencies_size () > 0) tty->print_cr(" dependencies [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2368 p2i(dependencies_begin()), 2369 p2i(dependencies_end()), 2370 dependencies_size()); 2371 if (handler_table_size() > 0) tty->print_cr(" handler table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2372 p2i(handler_table_begin()), 2373 p2i(handler_table_end()), 2374 handler_table_size()); 2375 if (nul_chk_table_size() > 0) tty->print_cr(" nul chk table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2376 p2i(nul_chk_table_begin()), 2377 p2i(nul_chk_table_end()), 2378 nul_chk_table_size()); 2379 } 2380 2381 #ifndef PRODUCT 2382 2383 void nmethod::print_scopes() { 2384 // Find the first pc desc for all scopes in the code and print it. 2385 ResourceMark rm; 2386 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) { 2387 if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null) 2388 continue; 2389 2390 ScopeDesc* sd = scope_desc_at(p->real_pc(this)); 2391 while (sd != NULL) { 2392 sd->print_on(tty, p); 2393 sd = sd->sender(); 2394 } 2395 } 2396 } 2397 2398 void nmethod::print_dependencies() { 2399 ResourceMark rm; 2400 ttyLocker ttyl; // keep the following output all in one block 2401 tty->print_cr("Dependencies:"); 2402 for (Dependencies::DepStream deps(this); deps.next(); ) { 2403 deps.print_dependency(); 2404 Klass* ctxk = deps.context_type(); 2405 if (ctxk != NULL) { 2406 if (ctxk->is_instance_klass() && InstanceKlass::cast(ctxk)->is_dependent_nmethod(this)) { 2407 tty->print_cr(" [nmethod<=klass]%s", ctxk->external_name()); 2408 } 2409 } 2410 deps.log_dependency(); // put it into the xml log also 2411 } 2412 } 2413 2414 2415 void nmethod::print_relocations() { 2416 ResourceMark m; // in case methods get printed via the debugger 2417 tty->print_cr("relocations:"); 2418 RelocIterator iter(this); 2419 iter.print(); 2420 } 2421 2422 2423 void nmethod::print_pcs() { 2424 ResourceMark m; // in case methods get printed via debugger 2425 tty->print_cr("pc-bytecode offsets:"); 2426 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) { 2427 p->print(this); 2428 } 2429 } 2430 2431 void nmethod::print_recorded_oops() { 2432 tty->print_cr("Recorded oops:"); 2433 for (int i = 0; i < oops_count(); i++) { 2434 oop o = oop_at(i); 2435 tty->print("#%3d: " INTPTR_FORMAT " ", i, p2i(o)); 2436 if (o == Universe::non_oop_word()) { 2437 tty->print("non-oop word"); 2438 } else { 2439 if (o != NULL) { 2440 o->print_value(); 2441 } else { 2442 tty->print_cr("NULL"); 2443 } 2444 } 2445 tty->cr(); 2446 } 2447 } 2448 2449 void nmethod::print_recorded_metadata() { 2450 tty->print_cr("Recorded metadata:"); 2451 for (int i = 0; i < metadata_count(); i++) { 2452 Metadata* m = metadata_at(i); 2453 tty->print("#%3d: " INTPTR_FORMAT " ", i, p2i(m)); 2454 if (m == (Metadata*)Universe::non_oop_word()) { 2455 tty->print("non-metadata word"); 2456 } else { 2457 Metadata::print_value_on_maybe_null(tty, m); 2458 } 2459 tty->cr(); 2460 } 2461 } 2462 2463 #endif // PRODUCT 2464 2465 const char* nmethod::reloc_string_for(u_char* begin, u_char* end) { 2466 RelocIterator iter(this, begin, end); 2467 bool have_one = false; 2468 while (iter.next()) { 2469 have_one = true; 2470 switch (iter.type()) { 2471 case relocInfo::none: return "no_reloc"; 2472 case relocInfo::oop_type: { 2473 stringStream st; 2474 oop_Relocation* r = iter.oop_reloc(); 2475 oop obj = r->oop_value(); 2476 st.print("oop("); 2477 if (obj == NULL) st.print("NULL"); 2478 else obj->print_value_on(&st); 2479 st.print(")"); 2480 return st.as_string(); 2481 } 2482 case relocInfo::metadata_type: { 2483 stringStream st; 2484 metadata_Relocation* r = iter.metadata_reloc(); 2485 Metadata* obj = r->metadata_value(); 2486 st.print("metadata("); 2487 if (obj == NULL) st.print("NULL"); 2488 else obj->print_value_on(&st); 2489 st.print(")"); 2490 return st.as_string(); 2491 } 2492 case relocInfo::runtime_call_type: 2493 case relocInfo::runtime_call_w_cp_type: { 2494 stringStream st; 2495 st.print("runtime_call"); 2496 CallRelocation* r = (CallRelocation*)iter.reloc(); 2497 address dest = r->destination(); 2498 CodeBlob* cb = CodeCache::find_blob(dest); 2499 if (cb != NULL) { 2500 st.print(" %s", cb->name()); 2501 } else { 2502 ResourceMark rm; 2503 const int buflen = 1024; 2504 char* buf = NEW_RESOURCE_ARRAY(char, buflen); 2505 int offset; 2506 if (os::dll_address_to_function_name(dest, buf, buflen, &offset)) { 2507 st.print(" %s", buf); 2508 if (offset != 0) { 2509 st.print("+%d", offset); 2510 } 2511 } 2512 } 2513 return st.as_string(); 2514 } 2515 case relocInfo::virtual_call_type: { 2516 stringStream st; 2517 st.print_raw("virtual_call"); 2518 virtual_call_Relocation* r = iter.virtual_call_reloc(); 2519 Method* m = r->method_value(); 2520 if (m != NULL) { 2521 assert(m->is_method(), ""); 2522 m->print_short_name(&st); 2523 } 2524 return st.as_string(); 2525 } 2526 case relocInfo::opt_virtual_call_type: { 2527 stringStream st; 2528 st.print_raw("optimized virtual_call"); 2529 opt_virtual_call_Relocation* r = iter.opt_virtual_call_reloc(); 2530 Method* m = r->method_value(); 2531 if (m != NULL) { 2532 assert(m->is_method(), ""); 2533 m->print_short_name(&st); 2534 } 2535 return st.as_string(); 2536 } 2537 case relocInfo::static_call_type: { 2538 stringStream st; 2539 st.print_raw("static_call"); 2540 static_call_Relocation* r = iter.static_call_reloc(); 2541 Method* m = r->method_value(); 2542 if (m != NULL) { 2543 assert(m->is_method(), ""); 2544 m->print_short_name(&st); 2545 } 2546 return st.as_string(); 2547 } 2548 case relocInfo::static_stub_type: return "static_stub"; 2549 case relocInfo::external_word_type: return "external_word"; 2550 case relocInfo::internal_word_type: return "internal_word"; 2551 case relocInfo::section_word_type: return "section_word"; 2552 case relocInfo::poll_type: return "poll"; 2553 case relocInfo::poll_return_type: return "poll_return"; 2554 case relocInfo::trampoline_stub_type: return "trampoline_stub"; 2555 case relocInfo::type_mask: return "type_bit_mask"; 2556 2557 default: 2558 break; 2559 } 2560 } 2561 return have_one ? "other" : NULL; 2562 } 2563 2564 // Return a the last scope in (begin..end] 2565 ScopeDesc* nmethod::scope_desc_in(address begin, address end) { 2566 PcDesc* p = pc_desc_near(begin+1); 2567 if (p != NULL && p->real_pc(this) <= end) { 2568 return new ScopeDesc(this, p->scope_decode_offset(), 2569 p->obj_decode_offset(), p->should_reexecute(), p->rethrow_exception(), 2570 p->return_oop()); 2571 } 2572 return NULL; 2573 } 2574 2575 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin) const { 2576 if (block_begin == entry_point()) stream->print_cr("[Entry Point]"); 2577 if (block_begin == verified_entry_point()) stream->print_cr("[Verified Entry Point]"); 2578 if (JVMCI_ONLY(_exception_offset >= 0 &&) block_begin == exception_begin()) stream->print_cr("[Exception Handler]"); 2579 if (block_begin == stub_begin()) stream->print_cr("[Stub Code]"); 2580 if (JVMCI_ONLY(_deopt_handler_begin != NULL &&) block_begin == deopt_handler_begin()) stream->print_cr("[Deopt Handler Code]"); 2581 2582 if (has_method_handle_invokes()) 2583 if (block_begin == deopt_mh_handler_begin()) stream->print_cr("[Deopt MH Handler Code]"); 2584 2585 if (block_begin == consts_begin()) stream->print_cr("[Constants]"); 2586 2587 if (block_begin == entry_point()) { 2588 methodHandle m = method(); 2589 if (m.not_null()) { 2590 stream->print(" # "); 2591 m->print_value_on(stream); 2592 stream->cr(); 2593 } 2594 if (m.not_null() && !is_osr_method()) { 2595 ResourceMark rm; 2596 int sizeargs = m->size_of_parameters(); 2597 BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs); 2598 VMRegPair* regs = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs); 2599 { 2600 int sig_index = 0; 2601 if (!m->is_static()) 2602 sig_bt[sig_index++] = T_OBJECT; // 'this' 2603 for (SignatureStream ss(m->signature()); !ss.at_return_type(); ss.next()) { 2604 BasicType t = ss.type(); 2605 sig_bt[sig_index++] = t; 2606 if (type2size[t] == 2) { 2607 sig_bt[sig_index++] = T_VOID; 2608 } else { 2609 assert(type2size[t] == 1, "size is 1 or 2"); 2610 } 2611 } 2612 assert(sig_index == sizeargs, ""); 2613 } 2614 const char* spname = "sp"; // make arch-specific? 2615 intptr_t out_preserve = SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs, false); 2616 int stack_slot_offset = this->frame_size() * wordSize; 2617 int tab1 = 14, tab2 = 24; 2618 int sig_index = 0; 2619 int arg_index = (m->is_static() ? 0 : -1); 2620 bool did_old_sp = false; 2621 for (SignatureStream ss(m->signature()); !ss.at_return_type(); ) { 2622 bool at_this = (arg_index == -1); 2623 bool at_old_sp = false; 2624 BasicType t = (at_this ? T_OBJECT : ss.type()); 2625 assert(t == sig_bt[sig_index], "sigs in sync"); 2626 if (at_this) 2627 stream->print(" # this: "); 2628 else 2629 stream->print(" # parm%d: ", arg_index); 2630 stream->move_to(tab1); 2631 VMReg fst = regs[sig_index].first(); 2632 VMReg snd = regs[sig_index].second(); 2633 if (fst->is_reg()) { 2634 stream->print("%s", fst->name()); 2635 if (snd->is_valid()) { 2636 stream->print(":%s", snd->name()); 2637 } 2638 } else if (fst->is_stack()) { 2639 int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset; 2640 if (offset == stack_slot_offset) at_old_sp = true; 2641 stream->print("[%s+0x%x]", spname, offset); 2642 } else { 2643 stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd); 2644 } 2645 stream->print(" "); 2646 stream->move_to(tab2); 2647 stream->print("= "); 2648 if (at_this) { 2649 m->method_holder()->print_value_on(stream); 2650 } else { 2651 bool did_name = false; 2652 if (!at_this && ss.is_object()) { 2653 Symbol* name = ss.as_symbol_or_null(); 2654 if (name != NULL) { 2655 name->print_value_on(stream); 2656 did_name = true; 2657 } 2658 } 2659 if (!did_name) 2660 stream->print("%s", type2name(t)); 2661 } 2662 if (at_old_sp) { 2663 stream->print(" (%s of caller)", spname); 2664 did_old_sp = true; 2665 } 2666 stream->cr(); 2667 sig_index += type2size[t]; 2668 arg_index += 1; 2669 if (!at_this) ss.next(); 2670 } 2671 if (!did_old_sp) { 2672 stream->print(" # "); 2673 stream->move_to(tab1); 2674 stream->print("[%s+0x%x]", spname, stack_slot_offset); 2675 stream->print(" (%s of caller)", spname); 2676 stream->cr(); 2677 } 2678 } 2679 } 2680 } 2681 2682 void nmethod::print_code_comment_on(outputStream* st, int column, u_char* begin, u_char* end) { 2683 // First, find an oopmap in (begin, end]. 2684 // We use the odd half-closed interval so that oop maps and scope descs 2685 // which are tied to the byte after a call are printed with the call itself. 2686 address base = code_begin(); 2687 ImmutableOopMapSet* oms = oop_maps(); 2688 if (oms != NULL) { 2689 for (int i = 0, imax = oms->count(); i < imax; i++) { 2690 const ImmutableOopMapPair* pair = oms->pair_at(i); 2691 const ImmutableOopMap* om = pair->get_from(oms); 2692 address pc = base + pair->pc_offset(); 2693 if (pc > begin) { 2694 if (pc <= end) { 2695 st->move_to(column); 2696 st->print("; "); 2697 om->print_on(st); 2698 } 2699 break; 2700 } 2701 } 2702 } 2703 2704 // Print any debug info present at this pc. 2705 ScopeDesc* sd = scope_desc_in(begin, end); 2706 if (sd != NULL) { 2707 st->move_to(column); 2708 if (sd->bci() == SynchronizationEntryBCI) { 2709 st->print(";*synchronization entry"); 2710 } else if (sd->bci() == AfterBci) { 2711 st->print(";* method exit (unlocked if synchronized)"); 2712 } else if (sd->bci() == UnwindBci) { 2713 st->print(";* unwind (locked if synchronized)"); 2714 } else if (sd->bci() == AfterExceptionBci) { 2715 st->print(";* unwind (unlocked if synchronized)"); 2716 } else if (sd->bci() == UnknownBci) { 2717 st->print(";* unknown"); 2718 } else if (sd->bci() == InvalidFrameStateBci) { 2719 st->print(";* invalid frame state"); 2720 } else { 2721 if (sd->method() == NULL) { 2722 st->print("method is NULL"); 2723 } else if (sd->method()->is_native()) { 2724 st->print("method is native"); 2725 } else { 2726 Bytecodes::Code bc = sd->method()->java_code_at(sd->bci()); 2727 st->print(";*%s", Bytecodes::name(bc)); 2728 switch (bc) { 2729 case Bytecodes::_invokevirtual: 2730 case Bytecodes::_invokespecial: 2731 case Bytecodes::_invokestatic: 2732 case Bytecodes::_invokeinterface: 2733 { 2734 Bytecode_invoke invoke(sd->method(), sd->bci()); 2735 st->print(" "); 2736 if (invoke.name() != NULL) 2737 invoke.name()->print_symbol_on(st); 2738 else 2739 st->print("<UNKNOWN>"); 2740 break; 2741 } 2742 case Bytecodes::_getfield: 2743 case Bytecodes::_putfield: 2744 case Bytecodes::_getstatic: 2745 case Bytecodes::_putstatic: 2746 { 2747 Bytecode_field field(sd->method(), sd->bci()); 2748 st->print(" "); 2749 if (field.name() != NULL) 2750 field.name()->print_symbol_on(st); 2751 else 2752 st->print("<UNKNOWN>"); 2753 } 2754 default: 2755 break; 2756 } 2757 } 2758 st->print(" {reexecute=%d rethrow=%d return_oop=%d}", sd->should_reexecute(), sd->rethrow_exception(), sd->return_oop()); 2759 } 2760 2761 // Print all scopes 2762 for (;sd != NULL; sd = sd->sender()) { 2763 st->move_to(column); 2764 st->print("; -"); 2765 if (sd->method() == NULL) { 2766 st->print("method is NULL"); 2767 } else { 2768 sd->method()->print_short_name(st); 2769 } 2770 int lineno = sd->method()->line_number_from_bci(sd->bci()); 2771 if (lineno != -1) { 2772 st->print("@%d (line %d)", sd->bci(), lineno); 2773 } else { 2774 st->print("@%d", sd->bci()); 2775 } 2776 st->cr(); 2777 } 2778 } 2779 2780 // Print relocation information 2781 const char* str = reloc_string_for(begin, end); 2782 if (str != NULL) { 2783 if (sd != NULL) st->cr(); 2784 st->move_to(column); 2785 st->print("; {%s}", str); 2786 } 2787 int cont_offset = ImplicitExceptionTable(this).at(begin - code_begin()); 2788 if (cont_offset != 0) { 2789 st->move_to(column); 2790 st->print("; implicit exception: dispatches to " INTPTR_FORMAT, p2i(code_begin() + cont_offset)); 2791 } 2792 2793 } 2794 2795 class DirectNativeCallWrapper: public NativeCallWrapper { 2796 private: 2797 NativeCall* _call; 2798 2799 public: 2800 DirectNativeCallWrapper(NativeCall* call) : _call(call) {} 2801 2802 virtual address destination() const { return _call->destination(); } 2803 virtual address instruction_address() const { return _call->instruction_address(); } 2804 virtual address next_instruction_address() const { return _call->next_instruction_address(); } 2805 virtual address return_address() const { return _call->return_address(); } 2806 2807 virtual address get_resolve_call_stub(bool is_optimized) const { 2808 if (is_optimized) { 2809 return SharedRuntime::get_resolve_opt_virtual_call_stub(); 2810 } 2811 return SharedRuntime::get_resolve_virtual_call_stub(); 2812 } 2813 2814 virtual void set_destination_mt_safe(address dest) { 2815 #if INCLUDE_AOT 2816 if (UseAOT) { 2817 CodeBlob* callee = CodeCache::find_blob(dest); 2818 CompiledMethod* cm = callee->as_compiled_method_or_null(); 2819 if (cm != NULL && cm->is_far_code()) { 2820 // Temporary fix, see JDK-8143106 2821 CompiledDirectStaticCall* csc = CompiledDirectStaticCall::at(instruction_address()); 2822 csc->set_to_far(methodHandle(cm->method()), dest); 2823 return; 2824 } 2825 } 2826 #endif 2827 _call->set_destination_mt_safe(dest); 2828 } 2829 2830 virtual void set_to_interpreted(const methodHandle& method, CompiledICInfo& info) { 2831 CompiledDirectStaticCall* csc = CompiledDirectStaticCall::at(instruction_address()); 2832 #if INCLUDE_AOT 2833 if (info.to_aot()) { 2834 csc->set_to_far(method, info.entry()); 2835 } else 2836 #endif 2837 { 2838 csc->set_to_interpreted(method, info.entry()); 2839 } 2840 } 2841 2842 virtual void verify() const { 2843 // make sure code pattern is actually a call imm32 instruction 2844 _call->verify(); 2845 _call->verify_alignment(); 2846 } 2847 2848 virtual void verify_resolve_call(address dest) const { 2849 CodeBlob* db = CodeCache::find_blob_unsafe(dest); 2850 assert(db != NULL && !db->is_adapter_blob(), "must use stub!"); 2851 } 2852 2853 virtual bool is_call_to_interpreted(address dest) const { 2854 CodeBlob* cb = CodeCache::find_blob(_call->instruction_address()); 2855 return cb->contains(dest); 2856 } 2857 2858 virtual bool is_safe_for_patching() const { return false; } 2859 2860 virtual NativeInstruction* get_load_instruction(virtual_call_Relocation* r) const { 2861 return nativeMovConstReg_at(r->cached_value()); 2862 } 2863 2864 virtual void *get_data(NativeInstruction* instruction) const { 2865 return (void*)((NativeMovConstReg*) instruction)->data(); 2866 } 2867 2868 virtual void set_data(NativeInstruction* instruction, intptr_t data) { 2869 ((NativeMovConstReg*) instruction)->set_data(data); 2870 } 2871 }; 2872 2873 NativeCallWrapper* nmethod::call_wrapper_at(address call) const { 2874 return new DirectNativeCallWrapper((NativeCall*) call); 2875 } 2876 2877 NativeCallWrapper* nmethod::call_wrapper_before(address return_pc) const { 2878 return new DirectNativeCallWrapper(nativeCall_before(return_pc)); 2879 } 2880 2881 address nmethod::call_instruction_address(address pc) const { 2882 if (NativeCall::is_call_before(pc)) { 2883 NativeCall *ncall = nativeCall_before(pc); 2884 return ncall->instruction_address(); 2885 } 2886 return NULL; 2887 } 2888 2889 CompiledStaticCall* nmethod::compiledStaticCall_at(Relocation* call_site) const { 2890 return CompiledDirectStaticCall::at(call_site); 2891 } 2892 2893 CompiledStaticCall* nmethod::compiledStaticCall_at(address call_site) const { 2894 return CompiledDirectStaticCall::at(call_site); 2895 } 2896 2897 CompiledStaticCall* nmethod::compiledStaticCall_before(address return_addr) const { 2898 return CompiledDirectStaticCall::before(return_addr); 2899 } 2900 2901 #ifndef PRODUCT 2902 2903 void nmethod::print_value_on(outputStream* st) const { 2904 st->print("nmethod"); 2905 print_on(st, NULL); 2906 } 2907 2908 void nmethod::print_calls(outputStream* st) { 2909 RelocIterator iter(this); 2910 while (iter.next()) { 2911 switch (iter.type()) { 2912 case relocInfo::virtual_call_type: 2913 case relocInfo::opt_virtual_call_type: { 2914 CompiledICLocker ml_verify(this); 2915 CompiledIC_at(&iter)->print(); 2916 break; 2917 } 2918 case relocInfo::static_call_type: 2919 st->print_cr("Static call at " INTPTR_FORMAT, p2i(iter.reloc()->addr())); 2920 CompiledDirectStaticCall::at(iter.reloc())->print(); 2921 break; 2922 default: 2923 break; 2924 } 2925 } 2926 } 2927 2928 void nmethod::print_handler_table() { 2929 ExceptionHandlerTable(this).print(); 2930 } 2931 2932 void nmethod::print_nul_chk_table() { 2933 ImplicitExceptionTable(this).print(code_begin()); 2934 } 2935 2936 void nmethod::print_statistics() { 2937 ttyLocker ttyl; 2938 if (xtty != NULL) xtty->head("statistics type='nmethod'"); 2939 native_nmethod_stats.print_native_nmethod_stats(); 2940 #ifdef COMPILER1 2941 c1_java_nmethod_stats.print_nmethod_stats("C1"); 2942 #endif 2943 #ifdef COMPILER2 2944 c2_java_nmethod_stats.print_nmethod_stats("C2"); 2945 #endif 2946 #if INCLUDE_JVMCI 2947 jvmci_java_nmethod_stats.print_nmethod_stats("JVMCI"); 2948 #endif 2949 unknown_java_nmethod_stats.print_nmethod_stats("Unknown"); 2950 DebugInformationRecorder::print_statistics(); 2951 #ifndef PRODUCT 2952 pc_nmethod_stats.print_pc_stats(); 2953 #endif 2954 Dependencies::print_statistics(); 2955 if (xtty != NULL) xtty->tail("statistics"); 2956 } 2957 2958 #endif // !PRODUCT 2959 2960 #if INCLUDE_JVMCI 2961 void nmethod::clear_jvmci_installed_code() { 2962 assert_locked_or_safepoint(Patching_lock); 2963 if (_jvmci_installed_code != NULL) { 2964 JNIHandles::destroy_weak_global(_jvmci_installed_code); 2965 _jvmci_installed_code = NULL; 2966 } 2967 } 2968 2969 void nmethod::clear_speculation_log() { 2970 assert_locked_or_safepoint(Patching_lock); 2971 if (_speculation_log != NULL) { 2972 JNIHandles::destroy_weak_global(_speculation_log); 2973 _speculation_log = NULL; 2974 } 2975 } 2976 2977 void nmethod::maybe_invalidate_installed_code() { 2978 if (!is_compiled_by_jvmci()) { 2979 return; 2980 } 2981 2982 assert(Patching_lock->is_locked() || 2983 SafepointSynchronize::is_at_safepoint(), "should be performed under a lock for consistency"); 2984 oop installed_code = JNIHandles::resolve(_jvmci_installed_code); 2985 if (installed_code != NULL) { 2986 // Update the values in the InstalledCode instance if it still refers to this nmethod 2987 nmethod* nm = (nmethod*)InstalledCode::address(installed_code); 2988 if (nm == this) { 2989 if (!is_alive() || is_unloading()) { 2990 // Break the link between nmethod and InstalledCode such that the nmethod 2991 // can subsequently be flushed safely. The link must be maintained while 2992 // the method could have live activations since invalidateInstalledCode 2993 // might want to invalidate all existing activations. 2994 InstalledCode::set_address(installed_code, 0); 2995 InstalledCode::set_entryPoint(installed_code, 0); 2996 } else if (is_not_entrant()) { 2997 // Remove the entry point so any invocation will fail but keep 2998 // the address link around that so that existing activations can 2999 // be invalidated. 3000 InstalledCode::set_entryPoint(installed_code, 0); 3001 } 3002 } 3003 } 3004 if (!is_alive() || is_unloading()) { 3005 // Clear these out after the nmethod has been unregistered and any 3006 // updates to the InstalledCode instance have been performed. 3007 clear_jvmci_installed_code(); 3008 clear_speculation_log(); 3009 } 3010 } 3011 3012 void nmethod::invalidate_installed_code(Handle installedCode, TRAPS) { 3013 if (installedCode() == NULL) { 3014 THROW(vmSymbols::java_lang_NullPointerException()); 3015 } 3016 jlong nativeMethod = InstalledCode::address(installedCode); 3017 nmethod* nm = (nmethod*)nativeMethod; 3018 if (nm == NULL) { 3019 // Nothing to do 3020 return; 3021 } 3022 3023 nmethodLocker nml(nm); 3024 #ifdef ASSERT 3025 { 3026 MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag); 3027 // This relationship can only be checked safely under a lock 3028 assert(!nm->is_alive() || nm->is_unloading() || nm->jvmci_installed_code() == installedCode(), "sanity check"); 3029 } 3030 #endif 3031 3032 if (nm->is_alive()) { 3033 // Invalidating the InstalledCode means we want the nmethod 3034 // to be deoptimized. 3035 nm->mark_for_deoptimization(); 3036 VM_Deoptimize op; 3037 VMThread::execute(&op); 3038 } 3039 3040 // Multiple threads could reach this point so we now need to 3041 // lock and re-check the link to the nmethod so that only one 3042 // thread clears it. 3043 MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag); 3044 if (InstalledCode::address(installedCode) == nativeMethod) { 3045 InstalledCode::set_address(installedCode, 0); 3046 } 3047 } 3048 3049 oop nmethod::jvmci_installed_code() { 3050 return JNIHandles::resolve(_jvmci_installed_code); 3051 } 3052 3053 oop nmethod::speculation_log() { 3054 return JNIHandles::resolve(_speculation_log); 3055 } 3056 3057 char* nmethod::jvmci_installed_code_name(char* buf, size_t buflen) const { 3058 if (!this->is_compiled_by_jvmci()) { 3059 return NULL; 3060 } 3061 oop installed_code = JNIHandles::resolve(_jvmci_installed_code); 3062 if (installed_code != NULL) { 3063 oop installed_code_name = NULL; 3064 if (installed_code->is_a(InstalledCode::klass())) { 3065 installed_code_name = InstalledCode::name(installed_code); 3066 } 3067 if (installed_code_name != NULL) { 3068 return java_lang_String::as_utf8_string(installed_code_name, buf, (int)buflen); 3069 } 3070 } 3071 return NULL; 3072 } 3073 #endif