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