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 1142 void nmethod::cleanup_inline_caches() { 1143 assert_locked_or_safepoint(CompiledIC_lock); 1144 1145 // If the method is not entrant or zombie then a JMP is plastered over the 1146 // first few bytes. If an oop in the old code was there, that oop 1147 // should not get GC'd. Skip the first few bytes of oops on 1148 // not-entrant methods. 1149 address low_boundary = verified_entry_point(); 1150 if (!is_in_use()) { 1151 low_boundary += NativeJump::instruction_size; 1152 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump. 1153 // This means that the low_boundary is going to be a little too high. 1154 // This shouldn't matter, since oops of non-entrant methods are never used. 1155 // In fact, why are we bothering to look at oops in a non-entrant method?? 1156 } 1157 1158 // Find all calls in an nmethod and clear the ones that point to non-entrant, 1159 // zombie and unloaded nmethods. 1160 ResourceMark rm; 1161 RelocIterator iter(this, low_boundary); 1162 while(iter.next()) { 1163 switch(iter.type()) { 1164 case relocInfo::virtual_call_type: 1165 case relocInfo::opt_virtual_call_type: { 1166 CompiledIC *ic = CompiledIC_at(&iter); 1167 // Ok, to lookup references to zombies here 1168 CodeBlob *cb = CodeCache::find_blob_unsafe(ic->ic_destination()); 1169 if( cb != NULL && cb->is_nmethod() ) { 1170 nmethod* nm = (nmethod*)cb; 1171 // Clean inline caches pointing to zombie, non-entrant and unloaded methods 1172 if (!nm->is_in_use() || (nm->method()->code() != nm)) ic->set_to_clean(is_alive()); 1173 } 1174 break; 1175 } 1176 case relocInfo::static_call_type: { 1177 CompiledStaticCall *csc = compiledStaticCall_at(iter.reloc()); 1178 CodeBlob *cb = CodeCache::find_blob_unsafe(csc->destination()); 1179 if( cb != NULL && cb->is_nmethod() ) { 1180 nmethod* nm = (nmethod*)cb; 1181 // Clean inline caches pointing to zombie, non-entrant and unloaded methods 1182 if (!nm->is_in_use() || (nm->method()->code() != nm)) csc->set_to_clean(); 1183 } 1184 break; 1185 } 1186 } 1187 } 1188 } 1189 1190 void nmethod::verify_clean_inline_caches() { 1191 assert_locked_or_safepoint(CompiledIC_lock); 1192 1193 // If the method is not entrant or zombie then a JMP is plastered over the 1194 // first few bytes. If an oop in the old code was there, that oop 1195 // should not get GC'd. Skip the first few bytes of oops on 1196 // not-entrant methods. 1197 address low_boundary = verified_entry_point(); 1198 if (!is_in_use()) { 1199 low_boundary += NativeJump::instruction_size; 1200 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump. 1201 // This means that the low_boundary is going to be a little too high. 1202 // This shouldn't matter, since oops of non-entrant methods are never used. 1203 // In fact, why are we bothering to look at oops in a non-entrant method?? 1204 } 1205 1206 ResourceMark rm; 1207 RelocIterator iter(this, low_boundary); 1208 while(iter.next()) { 1209 switch(iter.type()) { 1210 case relocInfo::virtual_call_type: 1211 case relocInfo::opt_virtual_call_type: { 1212 CompiledIC *ic = CompiledIC_at(&iter); 1213 // Ok, to lookup references to zombies here 1214 CodeBlob *cb = CodeCache::find_blob_unsafe(ic->ic_destination()); 1215 if( cb != NULL && cb->is_nmethod() ) { 1216 nmethod* nm = (nmethod*)cb; 1217 // Verify that inline caches pointing to both zombie and not_entrant methods are clean 1218 if (!nm->is_in_use() || (nm->method()->code() != nm)) { 1219 assert(ic->is_clean(), "IC should be clean"); 1220 } 1221 } 1222 break; 1223 } 1224 case relocInfo::static_call_type: { 1225 CompiledStaticCall *csc = compiledStaticCall_at(iter.reloc()); 1226 CodeBlob *cb = CodeCache::find_blob_unsafe(csc->destination()); 1227 if( cb != NULL && cb->is_nmethod() ) { 1228 nmethod* nm = (nmethod*)cb; 1229 // Verify that inline caches pointing to both zombie and not_entrant methods are clean 1230 if (!nm->is_in_use() || (nm->method()->code() != nm)) { 1231 assert(csc->is_clean(), "IC should be clean"); 1232 } 1233 } 1234 break; 1235 } 1236 } 1237 } 1238 } 1239 1240 int nmethod::verify_icholder_relocations() { 1241 int count = 0; 1242 1243 RelocIterator iter(this); 1244 while(iter.next()) { 1245 if (iter.type() == relocInfo::virtual_call_type) { 1246 if (CompiledIC::is_icholder_call_site(iter.virtual_call_reloc())) { 1247 CompiledIC *ic = CompiledIC_at(&iter); 1248 if (TraceCompiledIC) { 1249 tty->print("noticed icholder " INTPTR_FORMAT " ", p2i(ic->cached_icholder())); 1250 ic->print(); 1251 } 1252 assert(ic->cached_icholder() != NULL, "must be non-NULL"); 1253 count++; 1254 } 1255 } 1256 } 1257 1258 return count; 1259 } 1260 1261 // This is a private interface with the sweeper. 1262 void nmethod::mark_as_seen_on_stack() { 1263 assert(is_alive(), "Must be an alive method"); 1264 // Set the traversal mark to ensure that the sweeper does 2 1265 // cleaning passes before moving to zombie. 1266 set_stack_traversal_mark(NMethodSweeper::traversal_count()); 1267 } 1268 1269 // Tell if a non-entrant method can be converted to a zombie (i.e., 1270 // there are no activations on the stack, not in use by the VM, 1271 // and not in use by the ServiceThread) 1272 bool nmethod::can_convert_to_zombie() { 1273 assert(is_not_entrant(), "must be a non-entrant method"); 1274 1275 // Since the nmethod sweeper only does partial sweep the sweeper's traversal 1276 // count can be greater than the stack traversal count before it hits the 1277 // nmethod for the second time. 1278 return stack_traversal_mark()+1 < NMethodSweeper::traversal_count() && 1279 !is_locked_by_vm(); 1280 } 1281 1282 void nmethod::inc_decompile_count() { 1283 if (!is_compiled_by_c2() && !is_compiled_by_jvmci()) return; 1284 // Could be gated by ProfileTraps, but do not bother... 1285 Method* m = method(); 1286 if (m == NULL) return; 1287 MethodData* mdo = m->method_data(); 1288 if (mdo == NULL) return; 1289 // There is a benign race here. See comments in methodData.hpp. 1290 mdo->inc_decompile_count(); 1291 } 1292 1293 void nmethod::increase_unloading_clock() { 1294 _global_unloading_clock++; 1295 if (_global_unloading_clock == 0) { 1296 // _nmethods are allocated with _unloading_clock == 0, 1297 // so 0 is never used as a clock value. 1298 _global_unloading_clock = 1; 1299 } 1300 } 1301 1302 void nmethod::set_unloading_clock(unsigned char unloading_clock) { 1303 OrderAccess::release_store((volatile jubyte*)&_unloading_clock, unloading_clock); 1304 } 1305 1306 unsigned char nmethod::unloading_clock() { 1307 return (unsigned char)OrderAccess::load_acquire((volatile jubyte*)&_unloading_clock); 1308 } 1309 1310 void nmethod::make_unloaded(BoolObjectClosure* is_alive, oop cause) { 1311 1312 post_compiled_method_unload(); 1313 1314 // Since this nmethod is being unloaded, make sure that dependencies 1315 // recorded in instanceKlasses get flushed and pass non-NULL closure to 1316 // indicate that this work is being done during a GC. 1317 assert(Universe::heap()->is_gc_active(), "should only be called during gc"); 1318 assert(is_alive != NULL, "Should be non-NULL"); 1319 // A non-NULL is_alive closure indicates that this is being called during GC. 1320 flush_dependencies(is_alive); 1321 1322 // Break cycle between nmethod & method 1323 if (log_is_enabled(Trace, classunload)) { 1324 outputStream* log = LogHandle(classunload)::trace_stream(); 1325 log->print_cr("making nmethod " INTPTR_FORMAT 1326 " unloadable, Method*(" INTPTR_FORMAT 1327 "), cause(" INTPTR_FORMAT ")", 1328 p2i(this), p2i(_method), p2i(cause)); 1329 if (!Universe::heap()->is_gc_active()) 1330 cause->klass()->print_on(log); 1331 } 1332 // Unlink the osr method, so we do not look this up again 1333 if (is_osr_method()) { 1334 invalidate_osr_method(); 1335 } 1336 // If _method is already NULL the Method* is about to be unloaded, 1337 // so we don't have to break the cycle. Note that it is possible to 1338 // have the Method* live here, in case we unload the nmethod because 1339 // it is pointing to some oop (other than the Method*) being unloaded. 1340 if (_method != NULL) { 1341 // OSR methods point to the Method*, but the Method* does not 1342 // point back! 1343 if (_method->code() == this) { 1344 _method->clear_code(); // Break a cycle 1345 } 1346 _method = NULL; // Clear the method of this dead nmethod 1347 } 1348 1349 // Make the class unloaded - i.e., change state and notify sweeper 1350 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 1351 if (is_in_use()) { 1352 // Transitioning directly from live to unloaded -- so 1353 // we need to force a cache clean-up; remember this 1354 // for later on. 1355 CodeCache::set_needs_cache_clean(true); 1356 } 1357 1358 // Unregister must be done before the state change 1359 Universe::heap()->unregister_nmethod(this); 1360 1361 _state = unloaded; 1362 1363 // Log the unloading. 1364 log_state_change(); 1365 1366 #if INCLUDE_JVMCI 1367 // The method can only be unloaded after the pointer to the installed code 1368 // Java wrapper is no longer alive. Here we need to clear out this weak 1369 // reference to the dead object. Nulling out the reference has to happen 1370 // after the method is unregistered since the original value may be still 1371 // tracked by the rset. 1372 maybe_invalidate_installed_code(); 1373 // Clear these out after the nmethod has been unregistered and any 1374 // updates to the InstalledCode instance have been performed. 1375 _jvmci_installed_code = NULL; 1376 _speculation_log = NULL; 1377 #endif 1378 1379 // The Method* is gone at this point 1380 assert(_method == NULL, "Tautology"); 1381 1382 set_osr_link(NULL); 1383 //set_scavenge_root_link(NULL); // done by prune_scavenge_root_nmethods 1384 NMethodSweeper::report_state_change(this); 1385 } 1386 1387 void nmethod::invalidate_osr_method() { 1388 assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod"); 1389 #ifndef ASSERT 1390 // Make sure osr nmethod is invalidated only once 1391 if (!is_in_use()) { 1392 return; 1393 } 1394 #endif 1395 // Remove from list of active nmethods 1396 if (method() != NULL) { 1397 bool removed = method()->method_holder()->remove_osr_nmethod(this); 1398 assert(!removed || is_in_use(), "unused osr nmethod should be invalidated"); 1399 } 1400 } 1401 1402 void nmethod::log_state_change() const { 1403 if (LogCompilation) { 1404 if (xtty != NULL) { 1405 ttyLocker ttyl; // keep the following output all in one block 1406 if (_state == unloaded) { 1407 xtty->begin_elem("make_unloaded thread='" UINTX_FORMAT "'", 1408 os::current_thread_id()); 1409 } else { 1410 xtty->begin_elem("make_not_entrant thread='" UINTX_FORMAT "'%s", 1411 os::current_thread_id(), 1412 (_state == zombie ? " zombie='1'" : "")); 1413 } 1414 log_identity(xtty); 1415 xtty->stamp(); 1416 xtty->end_elem(); 1417 } 1418 } 1419 if (PrintCompilation && _state != unloaded) { 1420 print_on(tty, _state == zombie ? "made zombie" : "made not entrant"); 1421 } 1422 } 1423 1424 /** 1425 * Common functionality for both make_not_entrant and make_zombie 1426 */ 1427 bool nmethod::make_not_entrant_or_zombie(unsigned int state) { 1428 assert(state == zombie || state == not_entrant, "must be zombie or not_entrant"); 1429 assert(!is_zombie(), "should not already be a zombie"); 1430 1431 // Make sure neither the nmethod nor the method is flushed in case of a safepoint in code below. 1432 nmethodLocker nml(this); 1433 methodHandle the_method(method()); 1434 NoSafepointVerifier nsv; 1435 1436 // during patching, depending on the nmethod state we must notify the GC that 1437 // code has been unloaded, unregistering it. We cannot do this right while 1438 // holding the Patching_lock because we need to use the CodeCache_lock. This 1439 // would be prone to deadlocks. 1440 // This flag is used to remember whether we need to later lock and unregister. 1441 bool nmethod_needs_unregister = false; 1442 1443 { 1444 // invalidate osr nmethod before acquiring the patching lock since 1445 // they both acquire leaf locks and we don't want a deadlock. 1446 // This logic is equivalent to the logic below for patching the 1447 // verified entry point of regular methods. 1448 if (is_osr_method()) { 1449 // this effectively makes the osr nmethod not entrant 1450 invalidate_osr_method(); 1451 } 1452 1453 // Enter critical section. Does not block for safepoint. 1454 MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag); 1455 1456 if (_state == state) { 1457 // another thread already performed this transition so nothing 1458 // to do, but return false to indicate this. 1459 return false; 1460 } 1461 1462 // The caller can be calling the method statically or through an inline 1463 // cache call. 1464 if (!is_osr_method() && !is_not_entrant()) { 1465 NativeJump::patch_verified_entry(entry_point(), verified_entry_point(), 1466 SharedRuntime::get_handle_wrong_method_stub()); 1467 } 1468 1469 if (is_in_use() && update_recompile_counts()) { 1470 // It's a true state change, so mark the method as decompiled. 1471 // Do it only for transition from alive. 1472 inc_decompile_count(); 1473 } 1474 1475 // If the state is becoming a zombie, signal to unregister the nmethod with 1476 // the heap. 1477 // This nmethod may have already been unloaded during a full GC. 1478 if ((state == zombie) && !is_unloaded()) { 1479 nmethod_needs_unregister = true; 1480 } 1481 1482 // Must happen before state change. Otherwise we have a race condition in 1483 // nmethod::can_not_entrant_be_converted(). I.e., a method can immediately 1484 // transition its state from 'not_entrant' to 'zombie' without having to wait 1485 // for stack scanning. 1486 if (state == not_entrant) { 1487 mark_as_seen_on_stack(); 1488 OrderAccess::storestore(); 1489 } 1490 1491 // Change state 1492 _state = state; 1493 1494 // Log the transition once 1495 log_state_change(); 1496 1497 // Invalidate while holding the patching lock 1498 JVMCI_ONLY(maybe_invalidate_installed_code()); 1499 1500 // Remove nmethod from method. 1501 // We need to check if both the _code and _from_compiled_code_entry_point 1502 // refer to this nmethod because there is a race in setting these two fields 1503 // in Method* as seen in bugid 4947125. 1504 // If the vep() points to the zombie nmethod, the memory for the nmethod 1505 // could be flushed and the compiler and vtable stubs could still call 1506 // through it. 1507 if (method() != NULL && (method()->code() == this || 1508 method()->from_compiled_entry() == verified_entry_point())) { 1509 HandleMark hm; 1510 method()->clear_code(); 1511 } 1512 } // leave critical region under Patching_lock 1513 1514 // When the nmethod becomes zombie it is no longer alive so the 1515 // dependencies must be flushed. nmethods in the not_entrant 1516 // state will be flushed later when the transition to zombie 1517 // happens or they get unloaded. 1518 if (state == zombie) { 1519 { 1520 // Flushing dependencies must be done before any possible 1521 // safepoint can sneak in, otherwise the oops used by the 1522 // dependency logic could have become stale. 1523 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1524 if (nmethod_needs_unregister) { 1525 Universe::heap()->unregister_nmethod(this); 1526 #ifdef JVMCI 1527 _jvmci_installed_code = NULL; 1528 _speculation_log = NULL; 1529 #endif 1530 } 1531 flush_dependencies(NULL); 1532 } 1533 1534 // zombie only - if a JVMTI agent has enabled the CompiledMethodUnload 1535 // event and it hasn't already been reported for this nmethod then 1536 // report it now. The event may have been reported earlier if the GC 1537 // marked it for unloading). JvmtiDeferredEventQueue support means 1538 // we no longer go to a safepoint here. 1539 post_compiled_method_unload(); 1540 1541 #ifdef ASSERT 1542 // It's no longer safe to access the oops section since zombie 1543 // nmethods aren't scanned for GC. 1544 _oops_are_stale = true; 1545 #endif 1546 // the Method may be reclaimed by class unloading now that the 1547 // nmethod is in zombie state 1548 set_method(NULL); 1549 } else { 1550 assert(state == not_entrant, "other cases may need to be handled differently"); 1551 } 1552 1553 if (TraceCreateZombies) { 1554 ResourceMark m; 1555 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"); 1556 } 1557 1558 NMethodSweeper::report_state_change(this); 1559 return true; 1560 } 1561 1562 void nmethod::flush() { 1563 // Note that there are no valid oops in the nmethod anymore. 1564 assert(!is_osr_method() || is_unloaded() || is_zombie(), 1565 "osr nmethod must be unloaded or zombie before flushing"); 1566 assert(is_zombie() || is_osr_method(), "must be a zombie method"); 1567 assert (!is_locked_by_vm(), "locked methods shouldn't be flushed"); 1568 assert_locked_or_safepoint(CodeCache_lock); 1569 1570 // completely deallocate this method 1571 Events::log(JavaThread::current(), "flushing nmethod " INTPTR_FORMAT, p2i(this)); 1572 if (PrintMethodFlushing) { 1573 tty->print_cr("*flushing %s nmethod %3d/" INTPTR_FORMAT ". Live blobs:" UINT32_FORMAT 1574 "/Free CodeCache:" SIZE_FORMAT "Kb", 1575 is_osr_method() ? "osr" : "",_compile_id, p2i(this), CodeCache::blob_count(), 1576 CodeCache::unallocated_capacity(CodeCache::get_code_blob_type(this))/1024); 1577 } 1578 1579 // We need to deallocate any ExceptionCache data. 1580 // Note that we do not need to grab the nmethod lock for this, it 1581 // better be thread safe if we're disposing of it! 1582 ExceptionCache* ec = exception_cache(); 1583 set_exception_cache(NULL); 1584 while(ec != NULL) { 1585 ExceptionCache* next = ec->next(); 1586 delete ec; 1587 ec = next; 1588 } 1589 1590 if (on_scavenge_root_list()) { 1591 CodeCache::drop_scavenge_root_nmethod(this); 1592 } 1593 1594 #ifdef SHARK 1595 ((SharkCompiler *) compiler())->free_compiled_method(insts_begin()); 1596 #endif // SHARK 1597 1598 ((CodeBlob*)(this))->flush(); 1599 1600 CodeCache::free(this); 1601 } 1602 1603 // 1604 // Notify all classes this nmethod is dependent on that it is no 1605 // longer dependent. This should only be called in two situations. 1606 // First, when a nmethod transitions to a zombie all dependents need 1607 // to be clear. Since zombification happens at a safepoint there's no 1608 // synchronization issues. The second place is a little more tricky. 1609 // During phase 1 of mark sweep class unloading may happen and as a 1610 // result some nmethods may get unloaded. In this case the flushing 1611 // of dependencies must happen during phase 1 since after GC any 1612 // dependencies in the unloaded nmethod won't be updated, so 1613 // traversing the dependency information in unsafe. In that case this 1614 // function is called with a non-NULL argument and this function only 1615 // notifies instanceKlasses that are reachable 1616 1617 void nmethod::flush_dependencies(BoolObjectClosure* is_alive) { 1618 assert_locked_or_safepoint(CodeCache_lock); 1619 assert(Universe::heap()->is_gc_active() == (is_alive != NULL), 1620 "is_alive is non-NULL if and only if we are called during GC"); 1621 if (!has_flushed_dependencies()) { 1622 set_has_flushed_dependencies(); 1623 for (Dependencies::DepStream deps(this); deps.next(); ) { 1624 if (deps.type() == Dependencies::call_site_target_value) { 1625 // CallSite dependencies are managed on per-CallSite instance basis. 1626 oop call_site = deps.argument_oop(0); 1627 MethodHandles::remove_dependent_nmethod(call_site, this); 1628 } else { 1629 Klass* klass = deps.context_type(); 1630 if (klass == NULL) { 1631 continue; // ignore things like evol_method 1632 } 1633 // During GC the is_alive closure is non-NULL, and is used to 1634 // determine liveness of dependees that need to be updated. 1635 if (is_alive == NULL || klass->is_loader_alive(is_alive)) { 1636 // The GC defers deletion of this entry, since there might be multiple threads 1637 // iterating over the _dependencies graph. Other call paths are single-threaded 1638 // and may delete it immediately. 1639 bool delete_immediately = is_alive == NULL; 1640 InstanceKlass::cast(klass)->remove_dependent_nmethod(this, delete_immediately); 1641 } 1642 } 1643 } 1644 } 1645 } 1646 1647 1648 // If this oop is not live, the nmethod can be unloaded. 1649 bool nmethod::can_unload(BoolObjectClosure* is_alive, oop* root, bool unloading_occurred) { 1650 assert(root != NULL, "just checking"); 1651 oop obj = *root; 1652 if (obj == NULL || is_alive->do_object_b(obj)) { 1653 return false; 1654 } 1655 1656 // If ScavengeRootsInCode is true, an nmethod might be unloaded 1657 // simply because one of its constant oops has gone dead. 1658 // No actual classes need to be unloaded in order for this to occur. 1659 assert(unloading_occurred || ScavengeRootsInCode, "Inconsistency in unloading"); 1660 make_unloaded(is_alive, obj); 1661 return true; 1662 } 1663 1664 // ------------------------------------------------------------------ 1665 // post_compiled_method_load_event 1666 // new method for install_code() path 1667 // Transfer information from compilation to jvmti 1668 void nmethod::post_compiled_method_load_event() { 1669 1670 Method* moop = method(); 1671 HOTSPOT_COMPILED_METHOD_LOAD( 1672 (char *) moop->klass_name()->bytes(), 1673 moop->klass_name()->utf8_length(), 1674 (char *) moop->name()->bytes(), 1675 moop->name()->utf8_length(), 1676 (char *) moop->signature()->bytes(), 1677 moop->signature()->utf8_length(), 1678 insts_begin(), insts_size()); 1679 1680 if (JvmtiExport::should_post_compiled_method_load() || 1681 JvmtiExport::should_post_compiled_method_unload()) { 1682 get_and_cache_jmethod_id(); 1683 } 1684 1685 if (JvmtiExport::should_post_compiled_method_load()) { 1686 // Let the Service thread (which is a real Java thread) post the event 1687 MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag); 1688 JvmtiDeferredEventQueue::enqueue( 1689 JvmtiDeferredEvent::compiled_method_load_event(this)); 1690 } 1691 } 1692 1693 jmethodID nmethod::get_and_cache_jmethod_id() { 1694 if (_jmethod_id == NULL) { 1695 // Cache the jmethod_id since it can no longer be looked up once the 1696 // method itself has been marked for unloading. 1697 _jmethod_id = method()->jmethod_id(); 1698 } 1699 return _jmethod_id; 1700 } 1701 1702 void nmethod::post_compiled_method_unload() { 1703 if (unload_reported()) { 1704 // During unloading we transition to unloaded and then to zombie 1705 // and the unloading is reported during the first transition. 1706 return; 1707 } 1708 1709 assert(_method != NULL && !is_unloaded(), "just checking"); 1710 DTRACE_METHOD_UNLOAD_PROBE(method()); 1711 1712 // If a JVMTI agent has enabled the CompiledMethodUnload event then 1713 // post the event. Sometime later this nmethod will be made a zombie 1714 // by the sweeper but the Method* will not be valid at that point. 1715 // If the _jmethod_id is null then no load event was ever requested 1716 // so don't bother posting the unload. The main reason for this is 1717 // that the jmethodID is a weak reference to the Method* so if 1718 // it's being unloaded there's no way to look it up since the weak 1719 // ref will have been cleared. 1720 if (_jmethod_id != NULL && JvmtiExport::should_post_compiled_method_unload()) { 1721 assert(!unload_reported(), "already unloaded"); 1722 JvmtiDeferredEvent event = 1723 JvmtiDeferredEvent::compiled_method_unload_event(this, 1724 _jmethod_id, insts_begin()); 1725 if (SafepointSynchronize::is_at_safepoint()) { 1726 // Don't want to take the queueing lock. Add it as pending and 1727 // it will get enqueued later. 1728 JvmtiDeferredEventQueue::add_pending_event(event); 1729 } else { 1730 MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag); 1731 JvmtiDeferredEventQueue::enqueue(event); 1732 } 1733 } 1734 1735 // The JVMTI CompiledMethodUnload event can be enabled or disabled at 1736 // any time. As the nmethod is being unloaded now we mark it has 1737 // having the unload event reported - this will ensure that we don't 1738 // attempt to report the event in the unlikely scenario where the 1739 // event is enabled at the time the nmethod is made a zombie. 1740 set_unload_reported(); 1741 } 1742 1743 void static clean_ic_if_metadata_is_dead(CompiledIC *ic, BoolObjectClosure *is_alive) { 1744 if (ic->is_icholder_call()) { 1745 // The only exception is compiledICHolder oops which may 1746 // yet be marked below. (We check this further below). 1747 CompiledICHolder* cichk_oop = ic->cached_icholder(); 1748 1749 if (cichk_oop->holder_method()->method_holder()->is_loader_alive(is_alive) && 1750 cichk_oop->holder_klass()->is_loader_alive(is_alive)) { 1751 return; 1752 } 1753 } else { 1754 Metadata* ic_oop = ic->cached_metadata(); 1755 if (ic_oop != NULL) { 1756 if (ic_oop->is_klass()) { 1757 if (((Klass*)ic_oop)->is_loader_alive(is_alive)) { 1758 return; 1759 } 1760 } else if (ic_oop->is_method()) { 1761 if (((Method*)ic_oop)->method_holder()->is_loader_alive(is_alive)) { 1762 return; 1763 } 1764 } else { 1765 ShouldNotReachHere(); 1766 } 1767 } 1768 } 1769 1770 ic->set_to_clean(); 1771 } 1772 1773 // This is called at the end of the strong tracing/marking phase of a 1774 // GC to unload an nmethod if it contains otherwise unreachable 1775 // oops. 1776 1777 void nmethod::do_unloading(BoolObjectClosure* is_alive, bool unloading_occurred) { 1778 // Make sure the oop's ready to receive visitors 1779 assert(!is_zombie() && !is_unloaded(), 1780 "should not call follow on zombie or unloaded nmethod"); 1781 1782 // If the method is not entrant then a JMP is plastered over the 1783 // first few bytes. If an oop in the old code was there, that oop 1784 // should not get GC'd. Skip the first few bytes of oops on 1785 // not-entrant methods. 1786 address low_boundary = verified_entry_point(); 1787 if (is_not_entrant()) { 1788 low_boundary += NativeJump::instruction_size; 1789 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump. 1790 // (See comment above.) 1791 } 1792 1793 // The RedefineClasses() API can cause the class unloading invariant 1794 // to no longer be true. See jvmtiExport.hpp for details. 1795 // Also, leave a debugging breadcrumb in local flag. 1796 if (JvmtiExport::has_redefined_a_class()) { 1797 // This set of the unloading_occurred flag is done before the 1798 // call to post_compiled_method_unload() so that the unloading 1799 // of this nmethod is reported. 1800 unloading_occurred = true; 1801 } 1802 1803 // Exception cache 1804 clean_exception_cache(is_alive); 1805 1806 // If class unloading occurred we first iterate over all inline caches and 1807 // clear ICs where the cached oop is referring to an unloaded klass or method. 1808 // The remaining live cached oops will be traversed in the relocInfo::oop_type 1809 // iteration below. 1810 if (unloading_occurred) { 1811 RelocIterator iter(this, low_boundary); 1812 while(iter.next()) { 1813 if (iter.type() == relocInfo::virtual_call_type) { 1814 CompiledIC *ic = CompiledIC_at(&iter); 1815 clean_ic_if_metadata_is_dead(ic, is_alive); 1816 } 1817 } 1818 } 1819 1820 // Compiled code 1821 { 1822 RelocIterator iter(this, low_boundary); 1823 while (iter.next()) { 1824 if (iter.type() == relocInfo::oop_type) { 1825 oop_Relocation* r = iter.oop_reloc(); 1826 // In this loop, we must only traverse those oops directly embedded in 1827 // the code. Other oops (oop_index>0) are seen as part of scopes_oops. 1828 assert(1 == (r->oop_is_immediate()) + 1829 (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()), 1830 "oop must be found in exactly one place"); 1831 if (r->oop_is_immediate() && r->oop_value() != NULL) { 1832 if (can_unload(is_alive, r->oop_addr(), unloading_occurred)) { 1833 return; 1834 } 1835 } 1836 } 1837 } 1838 } 1839 1840 1841 // Scopes 1842 for (oop* p = oops_begin(); p < oops_end(); p++) { 1843 if (*p == Universe::non_oop_word()) continue; // skip non-oops 1844 if (can_unload(is_alive, p, unloading_occurred)) { 1845 return; 1846 } 1847 } 1848 1849 #if INCLUDE_JVMCI 1850 // Follow JVMCI method 1851 BarrierSet* bs = Universe::heap()->barrier_set(); 1852 if (_jvmci_installed_code != NULL) { 1853 if (_jvmci_installed_code->is_a(HotSpotNmethod::klass()) && HotSpotNmethod::isDefault(_jvmci_installed_code)) { 1854 if (!is_alive->do_object_b(_jvmci_installed_code)) { 1855 clear_jvmci_installed_code(); 1856 } 1857 } else { 1858 if (can_unload(is_alive, (oop*)&_jvmci_installed_code, unloading_occurred)) { 1859 return; 1860 } 1861 } 1862 } 1863 1864 if (_speculation_log != NULL) { 1865 if (!is_alive->do_object_b(_speculation_log)) { 1866 bs->write_ref_nmethod_pre(&_speculation_log, this); 1867 _speculation_log = NULL; 1868 bs->write_ref_nmethod_post(&_speculation_log, this); 1869 } 1870 } 1871 #endif 1872 1873 1874 // Ensure that all metadata is still alive 1875 verify_metadata_loaders(low_boundary, is_alive); 1876 } 1877 1878 template <class CompiledICorStaticCall> 1879 static bool clean_if_nmethod_is_unloaded(CompiledICorStaticCall *ic, address addr, BoolObjectClosure *is_alive, nmethod* from) { 1880 // Ok, to lookup references to zombies here 1881 CodeBlob *cb = CodeCache::find_blob_unsafe(addr); 1882 if (cb != NULL && cb->is_nmethod()) { 1883 nmethod* nm = (nmethod*)cb; 1884 1885 if (nm->unloading_clock() != nmethod::global_unloading_clock()) { 1886 // The nmethod has not been processed yet. 1887 return true; 1888 } 1889 1890 // Clean inline caches pointing to both zombie and not_entrant methods 1891 if (!nm->is_in_use() || (nm->method()->code() != nm)) { 1892 ic->set_to_clean(); 1893 assert(ic->is_clean(), "nmethod " PTR_FORMAT "not clean %s", p2i(from), from->method()->name_and_sig_as_C_string()); 1894 } 1895 } 1896 1897 return false; 1898 } 1899 1900 static bool clean_if_nmethod_is_unloaded(CompiledIC *ic, BoolObjectClosure *is_alive, nmethod* from) { 1901 return clean_if_nmethod_is_unloaded(ic, ic->ic_destination(), is_alive, from); 1902 } 1903 1904 static bool clean_if_nmethod_is_unloaded(CompiledStaticCall *csc, BoolObjectClosure *is_alive, nmethod* from) { 1905 return clean_if_nmethod_is_unloaded(csc, csc->destination(), is_alive, from); 1906 } 1907 1908 bool nmethod::unload_if_dead_at(RelocIterator* iter_at_oop, BoolObjectClosure *is_alive, bool unloading_occurred) { 1909 assert(iter_at_oop->type() == relocInfo::oop_type, "Wrong relocation type"); 1910 1911 oop_Relocation* r = iter_at_oop->oop_reloc(); 1912 // Traverse those oops directly embedded in the code. 1913 // Other oops (oop_index>0) are seen as part of scopes_oops. 1914 assert(1 == (r->oop_is_immediate()) + 1915 (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()), 1916 "oop must be found in exactly one place"); 1917 if (r->oop_is_immediate() && r->oop_value() != NULL) { 1918 // Unload this nmethod if the oop is dead. 1919 if (can_unload(is_alive, r->oop_addr(), unloading_occurred)) { 1920 return true;; 1921 } 1922 } 1923 1924 return false; 1925 } 1926 1927 1928 bool nmethod::do_unloading_parallel(BoolObjectClosure* is_alive, bool unloading_occurred) { 1929 ResourceMark rm; 1930 1931 // Make sure the oop's ready to receive visitors 1932 assert(!is_zombie() && !is_unloaded(), 1933 "should not call follow on zombie or unloaded nmethod"); 1934 1935 // If the method is not entrant then a JMP is plastered over the 1936 // first few bytes. If an oop in the old code was there, that oop 1937 // should not get GC'd. Skip the first few bytes of oops on 1938 // not-entrant methods. 1939 address low_boundary = verified_entry_point(); 1940 if (is_not_entrant()) { 1941 low_boundary += NativeJump::instruction_size; 1942 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump. 1943 // (See comment above.) 1944 } 1945 1946 // The RedefineClasses() API can cause the class unloading invariant 1947 // to no longer be true. See jvmtiExport.hpp for details. 1948 // Also, leave a debugging breadcrumb in local flag. 1949 if (JvmtiExport::has_redefined_a_class()) { 1950 // This set of the unloading_occurred flag is done before the 1951 // call to post_compiled_method_unload() so that the unloading 1952 // of this nmethod is reported. 1953 unloading_occurred = true; 1954 } 1955 1956 // Exception cache 1957 clean_exception_cache(is_alive); 1958 1959 bool is_unloaded = false; 1960 bool postponed = false; 1961 1962 RelocIterator iter(this, low_boundary); 1963 while(iter.next()) { 1964 1965 switch (iter.type()) { 1966 1967 case relocInfo::virtual_call_type: 1968 if (unloading_occurred) { 1969 // If class unloading occurred we first iterate over all inline caches and 1970 // clear ICs where the cached oop is referring to an unloaded klass or method. 1971 clean_ic_if_metadata_is_dead(CompiledIC_at(&iter), is_alive); 1972 } 1973 1974 postponed |= clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this); 1975 break; 1976 1977 case relocInfo::opt_virtual_call_type: 1978 postponed |= clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this); 1979 break; 1980 1981 case relocInfo::static_call_type: 1982 postponed |= clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), is_alive, this); 1983 break; 1984 1985 case relocInfo::oop_type: 1986 if (!is_unloaded) { 1987 is_unloaded = unload_if_dead_at(&iter, is_alive, unloading_occurred); 1988 } 1989 break; 1990 1991 case relocInfo::metadata_type: 1992 break; // nothing to do. 1993 } 1994 } 1995 1996 if (is_unloaded) { 1997 return postponed; 1998 } 1999 2000 // Scopes 2001 for (oop* p = oops_begin(); p < oops_end(); p++) { 2002 if (*p == Universe::non_oop_word()) continue; // skip non-oops 2003 if (can_unload(is_alive, p, unloading_occurred)) { 2004 is_unloaded = true; 2005 break; 2006 } 2007 } 2008 2009 if (is_unloaded) { 2010 return postponed; 2011 } 2012 2013 #if INCLUDE_JVMCI 2014 // Follow JVMCI method 2015 BarrierSet* bs = Universe::heap()->barrier_set(); 2016 if (_jvmci_installed_code != NULL) { 2017 if (_jvmci_installed_code->is_a(HotSpotNmethod::klass()) && HotSpotNmethod::isDefault(_jvmci_installed_code)) { 2018 if (!is_alive->do_object_b(_jvmci_installed_code)) { 2019 clear_jvmci_installed_code(); 2020 } 2021 } else { 2022 if (can_unload(is_alive, (oop*)&_jvmci_installed_code, unloading_occurred)) { 2023 is_unloaded = true; 2024 } 2025 } 2026 } 2027 2028 if (_speculation_log != NULL) { 2029 if (!is_alive->do_object_b(_speculation_log)) { 2030 bs->write_ref_nmethod_pre(&_speculation_log, this); 2031 _speculation_log = NULL; 2032 bs->write_ref_nmethod_post(&_speculation_log, this); 2033 } 2034 } 2035 #endif 2036 2037 // Ensure that all metadata is still alive 2038 verify_metadata_loaders(low_boundary, is_alive); 2039 2040 return postponed; 2041 } 2042 2043 void nmethod::do_unloading_parallel_postponed(BoolObjectClosure* is_alive, bool unloading_occurred) { 2044 ResourceMark rm; 2045 2046 // Make sure the oop's ready to receive visitors 2047 assert(!is_zombie(), 2048 "should not call follow on zombie nmethod"); 2049 2050 // If the method is not entrant then a JMP is plastered over the 2051 // first few bytes. If an oop in the old code was there, that oop 2052 // should not get GC'd. Skip the first few bytes of oops on 2053 // not-entrant methods. 2054 address low_boundary = verified_entry_point(); 2055 if (is_not_entrant()) { 2056 low_boundary += NativeJump::instruction_size; 2057 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump. 2058 // (See comment above.) 2059 } 2060 2061 RelocIterator iter(this, low_boundary); 2062 while(iter.next()) { 2063 2064 switch (iter.type()) { 2065 2066 case relocInfo::virtual_call_type: 2067 clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this); 2068 break; 2069 2070 case relocInfo::opt_virtual_call_type: 2071 clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this); 2072 break; 2073 2074 case relocInfo::static_call_type: 2075 clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), is_alive, this); 2076 break; 2077 } 2078 } 2079 } 2080 2081 #ifdef ASSERT 2082 2083 class CheckClass : AllStatic { 2084 static BoolObjectClosure* _is_alive; 2085 2086 // Check class_loader is alive for this bit of metadata. 2087 static void check_class(Metadata* md) { 2088 Klass* klass = NULL; 2089 if (md->is_klass()) { 2090 klass = ((Klass*)md); 2091 } else if (md->is_method()) { 2092 klass = ((Method*)md)->method_holder(); 2093 } else if (md->is_methodData()) { 2094 klass = ((MethodData*)md)->method()->method_holder(); 2095 } else { 2096 md->print(); 2097 ShouldNotReachHere(); 2098 } 2099 assert(klass->is_loader_alive(_is_alive), "must be alive"); 2100 } 2101 public: 2102 static void do_check_class(BoolObjectClosure* is_alive, nmethod* nm) { 2103 assert(SafepointSynchronize::is_at_safepoint(), "this is only ok at safepoint"); 2104 _is_alive = is_alive; 2105 nm->metadata_do(check_class); 2106 } 2107 }; 2108 2109 // This is called during a safepoint so can use static data 2110 BoolObjectClosure* CheckClass::_is_alive = NULL; 2111 #endif // ASSERT 2112 2113 2114 // Processing of oop references should have been sufficient to keep 2115 // all strong references alive. Any weak references should have been 2116 // cleared as well. Visit all the metadata and ensure that it's 2117 // really alive. 2118 void nmethod::verify_metadata_loaders(address low_boundary, BoolObjectClosure* is_alive) { 2119 #ifdef ASSERT 2120 RelocIterator iter(this, low_boundary); 2121 while (iter.next()) { 2122 // static_stub_Relocations may have dangling references to 2123 // Method*s so trim them out here. Otherwise it looks like 2124 // compiled code is maintaining a link to dead metadata. 2125 address static_call_addr = NULL; 2126 if (iter.type() == relocInfo::opt_virtual_call_type) { 2127 CompiledIC* cic = CompiledIC_at(&iter); 2128 if (!cic->is_call_to_interpreted()) { 2129 static_call_addr = iter.addr(); 2130 } 2131 } else if (iter.type() == relocInfo::static_call_type) { 2132 CompiledStaticCall* csc = compiledStaticCall_at(iter.reloc()); 2133 if (!csc->is_call_to_interpreted()) { 2134 static_call_addr = iter.addr(); 2135 } 2136 } 2137 if (static_call_addr != NULL) { 2138 RelocIterator sciter(this, low_boundary); 2139 while (sciter.next()) { 2140 if (sciter.type() == relocInfo::static_stub_type && 2141 sciter.static_stub_reloc()->static_call() == static_call_addr) { 2142 sciter.static_stub_reloc()->clear_inline_cache(); 2143 } 2144 } 2145 } 2146 } 2147 // Check that the metadata embedded in the nmethod is alive 2148 CheckClass::do_check_class(is_alive, this); 2149 #endif 2150 } 2151 2152 2153 // Iterate over metadata calling this function. Used by RedefineClasses 2154 void nmethod::metadata_do(void f(Metadata*)) { 2155 address low_boundary = verified_entry_point(); 2156 if (is_not_entrant()) { 2157 low_boundary += NativeJump::instruction_size; 2158 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump. 2159 // (See comment above.) 2160 } 2161 { 2162 // Visit all immediate references that are embedded in the instruction stream. 2163 RelocIterator iter(this, low_boundary); 2164 while (iter.next()) { 2165 if (iter.type() == relocInfo::metadata_type ) { 2166 metadata_Relocation* r = iter.metadata_reloc(); 2167 // In this metadata, we must only follow those metadatas directly embedded in 2168 // the code. Other metadatas (oop_index>0) are seen as part of 2169 // the metadata section below. 2170 assert(1 == (r->metadata_is_immediate()) + 2171 (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()), 2172 "metadata must be found in exactly one place"); 2173 if (r->metadata_is_immediate() && r->metadata_value() != NULL) { 2174 Metadata* md = r->metadata_value(); 2175 if (md != _method) f(md); 2176 } 2177 } else if (iter.type() == relocInfo::virtual_call_type) { 2178 // Check compiledIC holders associated with this nmethod 2179 CompiledIC *ic = CompiledIC_at(&iter); 2180 if (ic->is_icholder_call()) { 2181 CompiledICHolder* cichk = ic->cached_icholder(); 2182 f(cichk->holder_method()); 2183 f(cichk->holder_klass()); 2184 } else { 2185 Metadata* ic_oop = ic->cached_metadata(); 2186 if (ic_oop != NULL) { 2187 f(ic_oop); 2188 } 2189 } 2190 } 2191 } 2192 } 2193 2194 // Visit the metadata section 2195 for (Metadata** p = metadata_begin(); p < metadata_end(); p++) { 2196 if (*p == Universe::non_oop_word() || *p == NULL) continue; // skip non-oops 2197 Metadata* md = *p; 2198 f(md); 2199 } 2200 2201 // Visit metadata not embedded in the other places. 2202 if (_method != NULL) f(_method); 2203 } 2204 2205 void nmethod::oops_do(OopClosure* f, bool allow_zombie) { 2206 // make sure the oops ready to receive visitors 2207 assert(allow_zombie || !is_zombie(), "should not call follow on zombie nmethod"); 2208 assert(!is_unloaded(), "should not call follow on unloaded nmethod"); 2209 2210 // If the method is not entrant or zombie then a JMP is plastered over the 2211 // first few bytes. If an oop in the old code was there, that oop 2212 // should not get GC'd. Skip the first few bytes of oops on 2213 // not-entrant methods. 2214 address low_boundary = verified_entry_point(); 2215 if (is_not_entrant()) { 2216 low_boundary += NativeJump::instruction_size; 2217 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump. 2218 // (See comment above.) 2219 } 2220 2221 #if INCLUDE_JVMCI 2222 if (_jvmci_installed_code != NULL) { 2223 f->do_oop((oop*) &_jvmci_installed_code); 2224 } 2225 if (_speculation_log != NULL) { 2226 f->do_oop((oop*) &_speculation_log); 2227 } 2228 #endif 2229 2230 RelocIterator iter(this, low_boundary); 2231 2232 while (iter.next()) { 2233 if (iter.type() == relocInfo::oop_type ) { 2234 oop_Relocation* r = iter.oop_reloc(); 2235 // In this loop, we must only follow those oops directly embedded in 2236 // the code. Other oops (oop_index>0) are seen as part of scopes_oops. 2237 assert(1 == (r->oop_is_immediate()) + 2238 (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()), 2239 "oop must be found in exactly one place"); 2240 if (r->oop_is_immediate() && r->oop_value() != NULL) { 2241 f->do_oop(r->oop_addr()); 2242 } 2243 } 2244 } 2245 2246 // Scopes 2247 // This includes oop constants not inlined in the code stream. 2248 for (oop* p = oops_begin(); p < oops_end(); p++) { 2249 if (*p == Universe::non_oop_word()) continue; // skip non-oops 2250 f->do_oop(p); 2251 } 2252 } 2253 2254 #define NMETHOD_SENTINEL ((nmethod*)badAddress) 2255 2256 nmethod* volatile nmethod::_oops_do_mark_nmethods; 2257 2258 // An nmethod is "marked" if its _mark_link is set non-null. 2259 // Even if it is the end of the linked list, it will have a non-null link value, 2260 // as long as it is on the list. 2261 // This code must be MP safe, because it is used from parallel GC passes. 2262 bool nmethod::test_set_oops_do_mark() { 2263 assert(nmethod::oops_do_marking_is_active(), "oops_do_marking_prologue must be called"); 2264 nmethod* observed_mark_link = _oops_do_mark_link; 2265 if (observed_mark_link == NULL) { 2266 // Claim this nmethod for this thread to mark. 2267 observed_mark_link = (nmethod*) 2268 Atomic::cmpxchg_ptr(NMETHOD_SENTINEL, &_oops_do_mark_link, NULL); 2269 if (observed_mark_link == NULL) { 2270 2271 // Atomically append this nmethod (now claimed) to the head of the list: 2272 nmethod* observed_mark_nmethods = _oops_do_mark_nmethods; 2273 for (;;) { 2274 nmethod* required_mark_nmethods = observed_mark_nmethods; 2275 _oops_do_mark_link = required_mark_nmethods; 2276 observed_mark_nmethods = (nmethod*) 2277 Atomic::cmpxchg_ptr(this, &_oops_do_mark_nmethods, required_mark_nmethods); 2278 if (observed_mark_nmethods == required_mark_nmethods) 2279 break; 2280 } 2281 // Mark was clear when we first saw this guy. 2282 if (TraceScavenge) { print_on(tty, "oops_do, mark"); } 2283 return false; 2284 } 2285 } 2286 // On fall through, another racing thread marked this nmethod before we did. 2287 return true; 2288 } 2289 2290 void nmethod::oops_do_marking_prologue() { 2291 if (TraceScavenge) { tty->print_cr("[oops_do_marking_prologue"); } 2292 assert(_oops_do_mark_nmethods == NULL, "must not call oops_do_marking_prologue twice in a row"); 2293 // We use cmpxchg_ptr instead of regular assignment here because the user 2294 // may fork a bunch of threads, and we need them all to see the same state. 2295 void* observed = Atomic::cmpxchg_ptr(NMETHOD_SENTINEL, &_oops_do_mark_nmethods, NULL); 2296 guarantee(observed == NULL, "no races in this sequential code"); 2297 } 2298 2299 void nmethod::oops_do_marking_epilogue() { 2300 assert(_oops_do_mark_nmethods != NULL, "must not call oops_do_marking_epilogue twice in a row"); 2301 nmethod* cur = _oops_do_mark_nmethods; 2302 while (cur != NMETHOD_SENTINEL) { 2303 assert(cur != NULL, "not NULL-terminated"); 2304 nmethod* next = cur->_oops_do_mark_link; 2305 cur->_oops_do_mark_link = NULL; 2306 DEBUG_ONLY(cur->verify_oop_relocations()); 2307 NOT_PRODUCT(if (TraceScavenge) cur->print_on(tty, "oops_do, unmark")); 2308 cur = next; 2309 } 2310 void* required = _oops_do_mark_nmethods; 2311 void* observed = Atomic::cmpxchg_ptr(NULL, &_oops_do_mark_nmethods, required); 2312 guarantee(observed == required, "no races in this sequential code"); 2313 if (TraceScavenge) { tty->print_cr("oops_do_marking_epilogue]"); } 2314 } 2315 2316 class DetectScavengeRoot: public OopClosure { 2317 bool _detected_scavenge_root; 2318 public: 2319 DetectScavengeRoot() : _detected_scavenge_root(false) 2320 { NOT_PRODUCT(_print_nm = NULL); } 2321 bool detected_scavenge_root() { return _detected_scavenge_root; } 2322 virtual void do_oop(oop* p) { 2323 if ((*p) != NULL && (*p)->is_scavengable()) { 2324 NOT_PRODUCT(maybe_print(p)); 2325 _detected_scavenge_root = true; 2326 } 2327 } 2328 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); } 2329 2330 #ifndef PRODUCT 2331 nmethod* _print_nm; 2332 void maybe_print(oop* p) { 2333 if (_print_nm == NULL) return; 2334 if (!_detected_scavenge_root) _print_nm->print_on(tty, "new scavenge root"); 2335 tty->print_cr("" PTR_FORMAT "[offset=%d] detected scavengable oop " PTR_FORMAT " (found at " PTR_FORMAT ")", 2336 p2i(_print_nm), (int)((intptr_t)p - (intptr_t)_print_nm), 2337 p2i(*p), p2i(p)); 2338 (*p)->print(); 2339 } 2340 #endif //PRODUCT 2341 }; 2342 2343 bool nmethod::detect_scavenge_root_oops() { 2344 DetectScavengeRoot detect_scavenge_root; 2345 NOT_PRODUCT(if (TraceScavenge) detect_scavenge_root._print_nm = this); 2346 oops_do(&detect_scavenge_root); 2347 return detect_scavenge_root.detected_scavenge_root(); 2348 } 2349 2350 // Method that knows how to preserve outgoing arguments at call. This method must be 2351 // called with a frame corresponding to a Java invoke 2352 void nmethod::preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f) { 2353 #ifndef SHARK 2354 if (method() != NULL && !method()->is_native()) { 2355 address pc = fr.pc(); 2356 SimpleScopeDesc ssd(this, pc); 2357 Bytecode_invoke call(ssd.method(), ssd.bci()); 2358 bool has_receiver = call.has_receiver(); 2359 bool has_appendix = call.has_appendix(); 2360 Symbol* signature = call.signature(); 2361 2362 // The method attached by JIT-compilers should be used, if present. 2363 // Bytecode can be inaccurate in such case. 2364 Method* callee = attached_method_before_pc(pc); 2365 if (callee != NULL) { 2366 has_receiver = !(callee->access_flags().is_static()); 2367 has_appendix = false; 2368 signature = callee->signature(); 2369 } 2370 2371 fr.oops_compiled_arguments_do(signature, has_receiver, has_appendix, reg_map, f); 2372 } 2373 #endif // !SHARK 2374 } 2375 2376 inline bool includes(void* p, void* from, void* to) { 2377 return from <= p && p < to; 2378 } 2379 2380 2381 void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) { 2382 assert(count >= 2, "must be sentinel values, at least"); 2383 2384 #ifdef ASSERT 2385 // must be sorted and unique; we do a binary search in find_pc_desc() 2386 int prev_offset = pcs[0].pc_offset(); 2387 assert(prev_offset == PcDesc::lower_offset_limit, 2388 "must start with a sentinel"); 2389 for (int i = 1; i < count; i++) { 2390 int this_offset = pcs[i].pc_offset(); 2391 assert(this_offset > prev_offset, "offsets must be sorted"); 2392 prev_offset = this_offset; 2393 } 2394 assert(prev_offset == PcDesc::upper_offset_limit, 2395 "must end with a sentinel"); 2396 #endif //ASSERT 2397 2398 // Search for MethodHandle invokes and tag the nmethod. 2399 for (int i = 0; i < count; i++) { 2400 if (pcs[i].is_method_handle_invoke()) { 2401 set_has_method_handle_invokes(true); 2402 break; 2403 } 2404 } 2405 assert(has_method_handle_invokes() == (_deoptimize_mh_offset != -1), "must have deopt mh handler"); 2406 2407 int size = count * sizeof(PcDesc); 2408 assert(scopes_pcs_size() >= size, "oob"); 2409 memcpy(scopes_pcs_begin(), pcs, size); 2410 2411 // Adjust the final sentinel downward. 2412 PcDesc* last_pc = &scopes_pcs_begin()[count-1]; 2413 assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity"); 2414 last_pc->set_pc_offset(content_size() + 1); 2415 for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) { 2416 // Fill any rounding gaps with copies of the last record. 2417 last_pc[1] = last_pc[0]; 2418 } 2419 // The following assert could fail if sizeof(PcDesc) is not 2420 // an integral multiple of oopSize (the rounding term). 2421 // If it fails, change the logic to always allocate a multiple 2422 // of sizeof(PcDesc), and fill unused words with copies of *last_pc. 2423 assert(last_pc + 1 == scopes_pcs_end(), "must match exactly"); 2424 } 2425 2426 void nmethod::copy_scopes_data(u_char* buffer, int size) { 2427 assert(scopes_data_size() >= size, "oob"); 2428 memcpy(scopes_data_begin(), buffer, size); 2429 } 2430 2431 // When using JVMCI the address might be off by the size of a call instruction. 2432 bool nmethod::is_deopt_entry(address pc) { 2433 return pc == deopt_handler_begin() 2434 #if INCLUDE_JVMCI 2435 || pc == (deopt_handler_begin() + NativeCall::instruction_size) 2436 #endif 2437 ; 2438 } 2439 2440 #ifdef ASSERT 2441 static PcDesc* linear_search(nmethod* nm, int pc_offset, bool approximate) { 2442 PcDesc* lower = nm->scopes_pcs_begin(); 2443 PcDesc* upper = nm->scopes_pcs_end(); 2444 lower += 1; // exclude initial sentinel 2445 PcDesc* res = NULL; 2446 for (PcDesc* p = lower; p < upper; p++) { 2447 NOT_PRODUCT(--pc_nmethod_stats.pc_desc_tests); // don't count this call to match_desc 2448 if (match_desc(p, pc_offset, approximate)) { 2449 if (res == NULL) 2450 res = p; 2451 else 2452 res = (PcDesc*) badAddress; 2453 } 2454 } 2455 return res; 2456 } 2457 #endif 2458 2459 2460 // Finds a PcDesc with real-pc equal to "pc" 2461 PcDesc* nmethod::find_pc_desc_internal(address pc, bool approximate) { 2462 address base_address = code_begin(); 2463 if ((pc < base_address) || 2464 (pc - base_address) >= (ptrdiff_t) PcDesc::upper_offset_limit) { 2465 return NULL; // PC is wildly out of range 2466 } 2467 int pc_offset = (int) (pc - base_address); 2468 2469 // Check the PcDesc cache if it contains the desired PcDesc 2470 // (This as an almost 100% hit rate.) 2471 PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate); 2472 if (res != NULL) { 2473 assert(res == linear_search(this, pc_offset, approximate), "cache ok"); 2474 return res; 2475 } 2476 2477 // Fallback algorithm: quasi-linear search for the PcDesc 2478 // Find the last pc_offset less than the given offset. 2479 // The successor must be the required match, if there is a match at all. 2480 // (Use a fixed radix to avoid expensive affine pointer arithmetic.) 2481 PcDesc* lower = scopes_pcs_begin(); 2482 PcDesc* upper = scopes_pcs_end(); 2483 upper -= 1; // exclude final sentinel 2484 if (lower >= upper) return NULL; // native method; no PcDescs at all 2485 2486 #define assert_LU_OK \ 2487 /* invariant on lower..upper during the following search: */ \ 2488 assert(lower->pc_offset() < pc_offset, "sanity"); \ 2489 assert(upper->pc_offset() >= pc_offset, "sanity") 2490 assert_LU_OK; 2491 2492 // Use the last successful return as a split point. 2493 PcDesc* mid = _pc_desc_cache.last_pc_desc(); 2494 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches); 2495 if (mid->pc_offset() < pc_offset) { 2496 lower = mid; 2497 } else { 2498 upper = mid; 2499 } 2500 2501 // Take giant steps at first (4096, then 256, then 16, then 1) 2502 const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ debug_only(-1); 2503 const int RADIX = (1 << LOG2_RADIX); 2504 for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) { 2505 while ((mid = lower + step) < upper) { 2506 assert_LU_OK; 2507 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches); 2508 if (mid->pc_offset() < pc_offset) { 2509 lower = mid; 2510 } else { 2511 upper = mid; 2512 break; 2513 } 2514 } 2515 assert_LU_OK; 2516 } 2517 2518 // Sneak up on the value with a linear search of length ~16. 2519 while (true) { 2520 assert_LU_OK; 2521 mid = lower + 1; 2522 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches); 2523 if (mid->pc_offset() < pc_offset) { 2524 lower = mid; 2525 } else { 2526 upper = mid; 2527 break; 2528 } 2529 } 2530 #undef assert_LU_OK 2531 2532 if (match_desc(upper, pc_offset, approximate)) { 2533 assert(upper == linear_search(this, pc_offset, approximate), "search ok"); 2534 _pc_desc_cache.add_pc_desc(upper); 2535 return upper; 2536 } else { 2537 assert(NULL == linear_search(this, pc_offset, approximate), "search ok"); 2538 return NULL; 2539 } 2540 } 2541 2542 2543 void nmethod::check_all_dependencies(DepChange& changes) { 2544 // Checked dependencies are allocated into this ResourceMark 2545 ResourceMark rm; 2546 2547 // Turn off dependency tracing while actually testing dependencies. 2548 NOT_PRODUCT( FlagSetting fs(TraceDependencies, false) ); 2549 2550 typedef ResourceHashtable<DependencySignature, int, &DependencySignature::hash, 2551 &DependencySignature::equals, 11027> DepTable; 2552 2553 DepTable* table = new DepTable(); 2554 2555 // Iterate over live nmethods and check dependencies of all nmethods that are not 2556 // marked for deoptimization. A particular dependency is only checked once. 2557 NMethodIterator iter; 2558 while(iter.next()) { 2559 nmethod* nm = iter.method(); 2560 // Only notify for live nmethods 2561 if (nm->is_alive() && !nm->is_marked_for_deoptimization()) { 2562 for (Dependencies::DepStream deps(nm); deps.next(); ) { 2563 // Construct abstraction of a dependency. 2564 DependencySignature* current_sig = new DependencySignature(deps); 2565 2566 // Determine if dependency is already checked. table->put(...) returns 2567 // 'true' if the dependency is added (i.e., was not in the hashtable). 2568 if (table->put(*current_sig, 1)) { 2569 if (deps.check_dependency() != NULL) { 2570 // Dependency checking failed. Print out information about the failed 2571 // dependency and finally fail with an assert. We can fail here, since 2572 // dependency checking is never done in a product build. 2573 tty->print_cr("Failed dependency:"); 2574 changes.print(); 2575 nm->print(); 2576 nm->print_dependencies(); 2577 assert(false, "Should have been marked for deoptimization"); 2578 } 2579 } 2580 } 2581 } 2582 } 2583 } 2584 2585 bool nmethod::check_dependency_on(DepChange& changes) { 2586 // What has happened: 2587 // 1) a new class dependee has been added 2588 // 2) dependee and all its super classes have been marked 2589 bool found_check = false; // set true if we are upset 2590 for (Dependencies::DepStream deps(this); deps.next(); ) { 2591 // Evaluate only relevant dependencies. 2592 if (deps.spot_check_dependency_at(changes) != NULL) { 2593 found_check = true; 2594 NOT_DEBUG(break); 2595 } 2596 } 2597 return found_check; 2598 } 2599 2600 bool nmethod::is_evol_dependent_on(Klass* dependee) { 2601 InstanceKlass *dependee_ik = InstanceKlass::cast(dependee); 2602 Array<Method*>* dependee_methods = dependee_ik->methods(); 2603 for (Dependencies::DepStream deps(this); deps.next(); ) { 2604 if (deps.type() == Dependencies::evol_method) { 2605 Method* method = deps.method_argument(0); 2606 for (int j = 0; j < dependee_methods->length(); j++) { 2607 if (dependee_methods->at(j) == method) { 2608 // RC_TRACE macro has an embedded ResourceMark 2609 RC_TRACE(0x01000000, 2610 ("Found evol dependency of nmethod %s.%s(%s) compile_id=%d on method %s.%s(%s)", 2611 _method->method_holder()->external_name(), 2612 _method->name()->as_C_string(), 2613 _method->signature()->as_C_string(), compile_id(), 2614 method->method_holder()->external_name(), 2615 method->name()->as_C_string(), 2616 method->signature()->as_C_string())); 2617 if (TraceDependencies || LogCompilation) 2618 deps.log_dependency(dependee); 2619 return true; 2620 } 2621 } 2622 } 2623 } 2624 return false; 2625 } 2626 2627 // Called from mark_for_deoptimization, when dependee is invalidated. 2628 bool nmethod::is_dependent_on_method(Method* dependee) { 2629 for (Dependencies::DepStream deps(this); deps.next(); ) { 2630 if (deps.type() != Dependencies::evol_method) 2631 continue; 2632 Method* method = deps.method_argument(0); 2633 if (method == dependee) return true; 2634 } 2635 return false; 2636 } 2637 2638 2639 bool nmethod::is_patchable_at(address instr_addr) { 2640 assert(insts_contains(instr_addr), "wrong nmethod used"); 2641 if (is_zombie()) { 2642 // a zombie may never be patched 2643 return false; 2644 } 2645 return true; 2646 } 2647 2648 2649 address nmethod::continuation_for_implicit_exception(address pc) { 2650 // Exception happened outside inline-cache check code => we are inside 2651 // an active nmethod => use cpc to determine a return address 2652 int exception_offset = pc - code_begin(); 2653 int cont_offset = ImplicitExceptionTable(this).at( exception_offset ); 2654 #ifdef ASSERT 2655 if (cont_offset == 0) { 2656 Thread* thread = Thread::current(); 2657 ResetNoHandleMark rnm; // Might be called from LEAF/QUICK ENTRY 2658 HandleMark hm(thread); 2659 ResourceMark rm(thread); 2660 CodeBlob* cb = CodeCache::find_blob(pc); 2661 assert(cb != NULL && cb == this, ""); 2662 ttyLocker ttyl; 2663 tty->print_cr("implicit exception happened at " INTPTR_FORMAT, p2i(pc)); 2664 print(); 2665 method()->print_codes(); 2666 print_code(); 2667 print_pcs(); 2668 } 2669 #endif 2670 if (cont_offset == 0) { 2671 // Let the normal error handling report the exception 2672 return NULL; 2673 } 2674 return code_begin() + cont_offset; 2675 } 2676 2677 2678 2679 void nmethod_init() { 2680 // make sure you didn't forget to adjust the filler fields 2681 assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word"); 2682 } 2683 2684 2685 //------------------------------------------------------------------------------------------- 2686 2687 2688 // QQQ might we make this work from a frame?? 2689 nmethodLocker::nmethodLocker(address pc) { 2690 CodeBlob* cb = CodeCache::find_blob(pc); 2691 guarantee(cb != NULL && cb->is_nmethod(), "bad pc for a nmethod found"); 2692 _nm = (nmethod*)cb; 2693 lock_nmethod(_nm); 2694 } 2695 2696 // Only JvmtiDeferredEvent::compiled_method_unload_event() 2697 // should pass zombie_ok == true. 2698 void nmethodLocker::lock_nmethod(nmethod* nm, bool zombie_ok) { 2699 if (nm == NULL) return; 2700 Atomic::inc(&nm->_lock_count); 2701 assert(zombie_ok || !nm->is_zombie(), "cannot lock a zombie method"); 2702 } 2703 2704 void nmethodLocker::unlock_nmethod(nmethod* nm) { 2705 if (nm == NULL) return; 2706 Atomic::dec(&nm->_lock_count); 2707 assert(nm->_lock_count >= 0, "unmatched nmethod lock/unlock"); 2708 } 2709 2710 // ----------------------------------------------------------------------------- 2711 // nmethod::get_deopt_original_pc 2712 // 2713 // Return the original PC for the given PC if: 2714 // (a) the given PC belongs to a nmethod and 2715 // (b) it is a deopt PC 2716 address nmethod::get_deopt_original_pc(const frame* fr) { 2717 if (fr->cb() == NULL) return NULL; 2718 2719 nmethod* nm = fr->cb()->as_nmethod_or_null(); 2720 if (nm != NULL && nm->is_deopt_pc(fr->pc())) 2721 return nm->get_original_pc(fr); 2722 2723 return NULL; 2724 } 2725 2726 2727 // ----------------------------------------------------------------------------- 2728 // MethodHandle 2729 2730 bool nmethod::is_method_handle_return(address return_pc) { 2731 if (!has_method_handle_invokes()) return false; 2732 PcDesc* pd = pc_desc_at(return_pc); 2733 if (pd == NULL) 2734 return false; 2735 return pd->is_method_handle_invoke(); 2736 } 2737 2738 2739 // ----------------------------------------------------------------------------- 2740 // Verification 2741 2742 class VerifyOopsClosure: public OopClosure { 2743 nmethod* _nm; 2744 bool _ok; 2745 public: 2746 VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { } 2747 bool ok() { return _ok; } 2748 virtual void do_oop(oop* p) { 2749 if ((*p) == NULL || (*p)->is_oop()) return; 2750 if (_ok) { 2751 _nm->print_nmethod(true); 2752 _ok = false; 2753 } 2754 tty->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)", 2755 p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm)); 2756 } 2757 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); } 2758 }; 2759 2760 void nmethod::verify() { 2761 2762 // Hmm. OSR methods can be deopted but not marked as zombie or not_entrant 2763 // seems odd. 2764 2765 if (is_zombie() || is_not_entrant() || is_unloaded()) 2766 return; 2767 2768 // Make sure all the entry points are correctly aligned for patching. 2769 NativeJump::check_verified_entry_alignment(entry_point(), verified_entry_point()); 2770 2771 // assert(method()->is_oop(), "must be valid"); 2772 2773 ResourceMark rm; 2774 2775 if (!CodeCache::contains(this)) { 2776 fatal("nmethod at " INTPTR_FORMAT " not in zone", p2i(this)); 2777 } 2778 2779 if(is_native_method() ) 2780 return; 2781 2782 nmethod* nm = CodeCache::find_nmethod(verified_entry_point()); 2783 if (nm != this) { 2784 fatal("findNMethod did not find this nmethod (" INTPTR_FORMAT ")", p2i(this)); 2785 } 2786 2787 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) { 2788 if (! p->verify(this)) { 2789 tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", p2i(this)); 2790 } 2791 } 2792 2793 VerifyOopsClosure voc(this); 2794 oops_do(&voc); 2795 assert(voc.ok(), "embedded oops must be OK"); 2796 verify_scavenge_root_oops(); 2797 2798 verify_scopes(); 2799 } 2800 2801 2802 void nmethod::verify_interrupt_point(address call_site) { 2803 // Verify IC only when nmethod installation is finished. 2804 bool is_installed = (method()->code() == this) // nmethod is in state 'in_use' and installed 2805 || !this->is_in_use(); // nmethod is installed, but not in 'in_use' state 2806 if (is_installed) { 2807 Thread *cur = Thread::current(); 2808 if (CompiledIC_lock->owner() == cur || 2809 ((cur->is_VM_thread() || cur->is_ConcurrentGC_thread()) && 2810 SafepointSynchronize::is_at_safepoint())) { 2811 CompiledIC_at(this, call_site); 2812 CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops()); 2813 } else { 2814 MutexLocker ml_verify (CompiledIC_lock); 2815 CompiledIC_at(this, call_site); 2816 } 2817 } 2818 2819 PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address()); 2820 assert(pd != NULL, "PcDesc must exist"); 2821 for (ScopeDesc* sd = new ScopeDesc(this, pd->scope_decode_offset(), 2822 pd->obj_decode_offset(), pd->should_reexecute(), pd->rethrow_exception(), 2823 pd->return_oop()); 2824 !sd->is_top(); sd = sd->sender()) { 2825 sd->verify(); 2826 } 2827 } 2828 2829 void nmethod::verify_scopes() { 2830 if( !method() ) return; // Runtime stubs have no scope 2831 if (method()->is_native()) return; // Ignore stub methods. 2832 // iterate through all interrupt point 2833 // and verify the debug information is valid. 2834 RelocIterator iter((nmethod*)this); 2835 while (iter.next()) { 2836 address stub = NULL; 2837 switch (iter.type()) { 2838 case relocInfo::virtual_call_type: 2839 verify_interrupt_point(iter.addr()); 2840 break; 2841 case relocInfo::opt_virtual_call_type: 2842 stub = iter.opt_virtual_call_reloc()->static_stub(); 2843 verify_interrupt_point(iter.addr()); 2844 break; 2845 case relocInfo::static_call_type: 2846 stub = iter.static_call_reloc()->static_stub(); 2847 //verify_interrupt_point(iter.addr()); 2848 break; 2849 case relocInfo::runtime_call_type: 2850 address destination = iter.reloc()->value(); 2851 // Right now there is no way to find out which entries support 2852 // an interrupt point. It would be nice if we had this 2853 // information in a table. 2854 break; 2855 } 2856 assert(stub == NULL || stub_contains(stub), "static call stub outside stub section"); 2857 } 2858 } 2859 2860 2861 // ----------------------------------------------------------------------------- 2862 // Non-product code 2863 #ifndef PRODUCT 2864 2865 class DebugScavengeRoot: public OopClosure { 2866 nmethod* _nm; 2867 bool _ok; 2868 public: 2869 DebugScavengeRoot(nmethod* nm) : _nm(nm), _ok(true) { } 2870 bool ok() { return _ok; } 2871 virtual void do_oop(oop* p) { 2872 if ((*p) == NULL || !(*p)->is_scavengable()) return; 2873 if (_ok) { 2874 _nm->print_nmethod(true); 2875 _ok = false; 2876 } 2877 tty->print_cr("*** scavengable oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)", 2878 p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm)); 2879 (*p)->print(); 2880 } 2881 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); } 2882 }; 2883 2884 void nmethod::verify_scavenge_root_oops() { 2885 if (UseG1GC) { 2886 return; 2887 } 2888 2889 if (!on_scavenge_root_list()) { 2890 // Actually look inside, to verify the claim that it's clean. 2891 DebugScavengeRoot debug_scavenge_root(this); 2892 oops_do(&debug_scavenge_root); 2893 if (!debug_scavenge_root.ok()) 2894 fatal("found an unadvertised bad scavengable oop in the code cache"); 2895 } 2896 assert(scavenge_root_not_marked(), ""); 2897 } 2898 2899 #endif // PRODUCT 2900 2901 // Printing operations 2902 2903 void nmethod::print() const { 2904 ResourceMark rm; 2905 ttyLocker ttyl; // keep the following output all in one block 2906 2907 tty->print("Compiled method "); 2908 2909 if (is_compiled_by_c1()) { 2910 tty->print("(c1) "); 2911 } else if (is_compiled_by_c2()) { 2912 tty->print("(c2) "); 2913 } else if (is_compiled_by_shark()) { 2914 tty->print("(shark) "); 2915 } else if (is_compiled_by_jvmci()) { 2916 tty->print("(JVMCI) "); 2917 } else { 2918 tty->print("(nm) "); 2919 } 2920 2921 print_on(tty, NULL); 2922 2923 if (WizardMode) { 2924 tty->print("((nmethod*) " INTPTR_FORMAT ") ", p2i(this)); 2925 tty->print(" for method " INTPTR_FORMAT , p2i(method())); 2926 tty->print(" { "); 2927 tty->print_cr("%s ", state()); 2928 if (on_scavenge_root_list()) tty->print("scavenge_root "); 2929 tty->print_cr("}:"); 2930 } 2931 if (size () > 0) tty->print_cr(" total in heap [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2932 p2i(this), 2933 p2i(this) + size(), 2934 size()); 2935 if (relocation_size () > 0) tty->print_cr(" relocation [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2936 p2i(relocation_begin()), 2937 p2i(relocation_end()), 2938 relocation_size()); 2939 if (consts_size () > 0) tty->print_cr(" constants [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2940 p2i(consts_begin()), 2941 p2i(consts_end()), 2942 consts_size()); 2943 if (insts_size () > 0) tty->print_cr(" main code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2944 p2i(insts_begin()), 2945 p2i(insts_end()), 2946 insts_size()); 2947 if (stub_size () > 0) tty->print_cr(" stub code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2948 p2i(stub_begin()), 2949 p2i(stub_end()), 2950 stub_size()); 2951 if (oops_size () > 0) tty->print_cr(" oops [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2952 p2i(oops_begin()), 2953 p2i(oops_end()), 2954 oops_size()); 2955 if (metadata_size () > 0) tty->print_cr(" metadata [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2956 p2i(metadata_begin()), 2957 p2i(metadata_end()), 2958 metadata_size()); 2959 if (scopes_data_size () > 0) tty->print_cr(" scopes data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2960 p2i(scopes_data_begin()), 2961 p2i(scopes_data_end()), 2962 scopes_data_size()); 2963 if (scopes_pcs_size () > 0) tty->print_cr(" scopes pcs [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2964 p2i(scopes_pcs_begin()), 2965 p2i(scopes_pcs_end()), 2966 scopes_pcs_size()); 2967 if (dependencies_size () > 0) tty->print_cr(" dependencies [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2968 p2i(dependencies_begin()), 2969 p2i(dependencies_end()), 2970 dependencies_size()); 2971 if (handler_table_size() > 0) tty->print_cr(" handler table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2972 p2i(handler_table_begin()), 2973 p2i(handler_table_end()), 2974 handler_table_size()); 2975 if (nul_chk_table_size() > 0) tty->print_cr(" nul chk table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2976 p2i(nul_chk_table_begin()), 2977 p2i(nul_chk_table_end()), 2978 nul_chk_table_size()); 2979 } 2980 2981 #ifndef PRODUCT 2982 2983 void nmethod::print_scopes() { 2984 // Find the first pc desc for all scopes in the code and print it. 2985 ResourceMark rm; 2986 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) { 2987 if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null) 2988 continue; 2989 2990 ScopeDesc* sd = scope_desc_at(p->real_pc(this)); 2991 while (sd != NULL) { 2992 sd->print_on(tty, p); 2993 sd = sd->sender(); 2994 } 2995 } 2996 } 2997 2998 void nmethod::print_dependencies() { 2999 ResourceMark rm; 3000 ttyLocker ttyl; // keep the following output all in one block 3001 tty->print_cr("Dependencies:"); 3002 for (Dependencies::DepStream deps(this); deps.next(); ) { 3003 deps.print_dependency(); 3004 Klass* ctxk = deps.context_type(); 3005 if (ctxk != NULL) { 3006 if (ctxk->is_instance_klass() && InstanceKlass::cast(ctxk)->is_dependent_nmethod(this)) { 3007 tty->print_cr(" [nmethod<=klass]%s", ctxk->external_name()); 3008 } 3009 } 3010 deps.log_dependency(); // put it into the xml log also 3011 } 3012 } 3013 3014 3015 void nmethod::print_relocations() { 3016 ResourceMark m; // in case methods get printed via the debugger 3017 tty->print_cr("relocations:"); 3018 RelocIterator iter(this); 3019 iter.print(); 3020 if (UseRelocIndex) { 3021 jint* index_end = (jint*)relocation_end() - 1; 3022 jint index_size = *index_end; 3023 jint* index_start = (jint*)( (address)index_end - index_size ); 3024 tty->print_cr(" index @" INTPTR_FORMAT ": index_size=%d", p2i(index_start), index_size); 3025 if (index_size > 0) { 3026 jint* ip; 3027 for (ip = index_start; ip+2 <= index_end; ip += 2) 3028 tty->print_cr(" (%d %d) addr=" INTPTR_FORMAT " @" INTPTR_FORMAT, 3029 ip[0], 3030 ip[1], 3031 p2i(header_end()+ip[0]), 3032 p2i(relocation_begin()-1+ip[1])); 3033 for (; ip < index_end; ip++) 3034 tty->print_cr(" (%d ?)", ip[0]); 3035 tty->print_cr(" @" INTPTR_FORMAT ": index_size=%d", p2i(ip), *ip); 3036 ip++; 3037 tty->print_cr("reloc_end @" INTPTR_FORMAT ":", p2i(ip)); 3038 } 3039 } 3040 } 3041 3042 3043 void nmethod::print_pcs() { 3044 ResourceMark m; // in case methods get printed via debugger 3045 tty->print_cr("pc-bytecode offsets:"); 3046 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) { 3047 p->print(this); 3048 } 3049 } 3050 3051 void nmethod::print_recorded_oops() { 3052 tty->print_cr("Recorded oops:"); 3053 for (int i = 0; i < oops_count(); i++) { 3054 oop o = oop_at(i); 3055 tty->print("#%3d: " INTPTR_FORMAT " ", i, p2i(o)); 3056 if (o == (oop)Universe::non_oop_word()) { 3057 tty->print("non-oop word"); 3058 } else { 3059 o->print_value(); 3060 } 3061 tty->cr(); 3062 } 3063 } 3064 3065 void nmethod::print_recorded_metadata() { 3066 tty->print_cr("Recorded metadata:"); 3067 for (int i = 0; i < metadata_count(); i++) { 3068 Metadata* m = metadata_at(i); 3069 tty->print("#%3d: " INTPTR_FORMAT " ", i, p2i(m)); 3070 if (m == (Metadata*)Universe::non_oop_word()) { 3071 tty->print("non-metadata word"); 3072 } else { 3073 m->print_value_on_maybe_null(tty); 3074 } 3075 tty->cr(); 3076 } 3077 } 3078 3079 #endif // PRODUCT 3080 3081 const char* nmethod::reloc_string_for(u_char* begin, u_char* end) { 3082 RelocIterator iter(this, begin, end); 3083 bool have_one = false; 3084 while (iter.next()) { 3085 have_one = true; 3086 switch (iter.type()) { 3087 case relocInfo::none: return "no_reloc"; 3088 case relocInfo::oop_type: { 3089 stringStream st; 3090 oop_Relocation* r = iter.oop_reloc(); 3091 oop obj = r->oop_value(); 3092 st.print("oop("); 3093 if (obj == NULL) st.print("NULL"); 3094 else obj->print_value_on(&st); 3095 st.print(")"); 3096 return st.as_string(); 3097 } 3098 case relocInfo::metadata_type: { 3099 stringStream st; 3100 metadata_Relocation* r = iter.metadata_reloc(); 3101 Metadata* obj = r->metadata_value(); 3102 st.print("metadata("); 3103 if (obj == NULL) st.print("NULL"); 3104 else obj->print_value_on(&st); 3105 st.print(")"); 3106 return st.as_string(); 3107 } 3108 case relocInfo::runtime_call_type: { 3109 stringStream st; 3110 st.print("runtime_call"); 3111 runtime_call_Relocation* r = iter.runtime_call_reloc(); 3112 address dest = r->destination(); 3113 CodeBlob* cb = CodeCache::find_blob(dest); 3114 if (cb != NULL) { 3115 st.print(" %s", cb->name()); 3116 } else { 3117 ResourceMark rm; 3118 const int buflen = 1024; 3119 char* buf = NEW_RESOURCE_ARRAY(char, buflen); 3120 int offset; 3121 if (os::dll_address_to_function_name(dest, buf, buflen, &offset)) { 3122 st.print(" %s", buf); 3123 if (offset != 0) { 3124 st.print("+%d", offset); 3125 } 3126 } 3127 } 3128 return st.as_string(); 3129 } 3130 case relocInfo::virtual_call_type: { 3131 stringStream st; 3132 st.print_raw("virtual_call"); 3133 virtual_call_Relocation* r = iter.virtual_call_reloc(); 3134 Method* m = r->method_value(); 3135 if (m != NULL) { 3136 assert(m->is_method(), ""); 3137 m->print_short_name(&st); 3138 } 3139 return st.as_string(); 3140 } 3141 case relocInfo::opt_virtual_call_type: { 3142 stringStream st; 3143 st.print_raw("optimized virtual_call"); 3144 opt_virtual_call_Relocation* r = iter.opt_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::static_call_type: { 3153 stringStream st; 3154 st.print_raw("static_call"); 3155 static_call_Relocation* r = iter.static_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_stub_type: return "static_stub"; 3164 case relocInfo::external_word_type: return "external_word"; 3165 case relocInfo::internal_word_type: return "internal_word"; 3166 case relocInfo::section_word_type: return "section_word"; 3167 case relocInfo::poll_type: return "poll"; 3168 case relocInfo::poll_return_type: return "poll_return"; 3169 case relocInfo::type_mask: return "type_bit_mask"; 3170 } 3171 } 3172 return have_one ? "other" : NULL; 3173 } 3174 3175 // Return a the last scope in (begin..end] 3176 ScopeDesc* nmethod::scope_desc_in(address begin, address end) { 3177 PcDesc* p = pc_desc_near(begin+1); 3178 if (p != NULL && p->real_pc(this) <= end) { 3179 return new ScopeDesc(this, p->scope_decode_offset(), 3180 p->obj_decode_offset(), p->should_reexecute(), p->rethrow_exception(), 3181 p->return_oop()); 3182 } 3183 return NULL; 3184 } 3185 3186 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin) const { 3187 if (block_begin == entry_point()) stream->print_cr("[Entry Point]"); 3188 if (block_begin == verified_entry_point()) stream->print_cr("[Verified Entry Point]"); 3189 if (JVMCI_ONLY(_exception_offset >= 0 &&) block_begin == exception_begin()) stream->print_cr("[Exception Handler]"); 3190 if (block_begin == stub_begin()) stream->print_cr("[Stub Code]"); 3191 if (JVMCI_ONLY(_deoptimize_offset >= 0 &&) block_begin == deopt_handler_begin()) stream->print_cr("[Deopt Handler Code]"); 3192 3193 if (has_method_handle_invokes()) 3194 if (block_begin == deopt_mh_handler_begin()) stream->print_cr("[Deopt MH Handler Code]"); 3195 3196 if (block_begin == consts_begin()) stream->print_cr("[Constants]"); 3197 3198 if (block_begin == entry_point()) { 3199 methodHandle m = method(); 3200 if (m.not_null()) { 3201 stream->print(" # "); 3202 m->print_value_on(stream); 3203 stream->cr(); 3204 } 3205 if (m.not_null() && !is_osr_method()) { 3206 ResourceMark rm; 3207 int sizeargs = m->size_of_parameters(); 3208 BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs); 3209 VMRegPair* regs = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs); 3210 { 3211 int sig_index = 0; 3212 if (!m->is_static()) 3213 sig_bt[sig_index++] = T_OBJECT; // 'this' 3214 for (SignatureStream ss(m->signature()); !ss.at_return_type(); ss.next()) { 3215 BasicType t = ss.type(); 3216 sig_bt[sig_index++] = t; 3217 if (type2size[t] == 2) { 3218 sig_bt[sig_index++] = T_VOID; 3219 } else { 3220 assert(type2size[t] == 1, "size is 1 or 2"); 3221 } 3222 } 3223 assert(sig_index == sizeargs, ""); 3224 } 3225 const char* spname = "sp"; // make arch-specific? 3226 intptr_t out_preserve = SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs, false); 3227 int stack_slot_offset = this->frame_size() * wordSize; 3228 int tab1 = 14, tab2 = 24; 3229 int sig_index = 0; 3230 int arg_index = (m->is_static() ? 0 : -1); 3231 bool did_old_sp = false; 3232 for (SignatureStream ss(m->signature()); !ss.at_return_type(); ) { 3233 bool at_this = (arg_index == -1); 3234 bool at_old_sp = false; 3235 BasicType t = (at_this ? T_OBJECT : ss.type()); 3236 assert(t == sig_bt[sig_index], "sigs in sync"); 3237 if (at_this) 3238 stream->print(" # this: "); 3239 else 3240 stream->print(" # parm%d: ", arg_index); 3241 stream->move_to(tab1); 3242 VMReg fst = regs[sig_index].first(); 3243 VMReg snd = regs[sig_index].second(); 3244 if (fst->is_reg()) { 3245 stream->print("%s", fst->name()); 3246 if (snd->is_valid()) { 3247 stream->print(":%s", snd->name()); 3248 } 3249 } else if (fst->is_stack()) { 3250 int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset; 3251 if (offset == stack_slot_offset) at_old_sp = true; 3252 stream->print("[%s+0x%x]", spname, offset); 3253 } else { 3254 stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd); 3255 } 3256 stream->print(" "); 3257 stream->move_to(tab2); 3258 stream->print("= "); 3259 if (at_this) { 3260 m->method_holder()->print_value_on(stream); 3261 } else { 3262 bool did_name = false; 3263 if (!at_this && ss.is_object()) { 3264 Symbol* name = ss.as_symbol_or_null(); 3265 if (name != NULL) { 3266 name->print_value_on(stream); 3267 did_name = true; 3268 } 3269 } 3270 if (!did_name) 3271 stream->print("%s", type2name(t)); 3272 } 3273 if (at_old_sp) { 3274 stream->print(" (%s of caller)", spname); 3275 did_old_sp = true; 3276 } 3277 stream->cr(); 3278 sig_index += type2size[t]; 3279 arg_index += 1; 3280 if (!at_this) ss.next(); 3281 } 3282 if (!did_old_sp) { 3283 stream->print(" # "); 3284 stream->move_to(tab1); 3285 stream->print("[%s+0x%x]", spname, stack_slot_offset); 3286 stream->print(" (%s of caller)", spname); 3287 stream->cr(); 3288 } 3289 } 3290 } 3291 } 3292 3293 void nmethod::print_code_comment_on(outputStream* st, int column, u_char* begin, u_char* end) { 3294 // First, find an oopmap in (begin, end]. 3295 // We use the odd half-closed interval so that oop maps and scope descs 3296 // which are tied to the byte after a call are printed with the call itself. 3297 address base = code_begin(); 3298 ImmutableOopMapSet* oms = oop_maps(); 3299 if (oms != NULL) { 3300 for (int i = 0, imax = oms->count(); i < imax; i++) { 3301 const ImmutableOopMapPair* pair = oms->pair_at(i); 3302 const ImmutableOopMap* om = pair->get_from(oms); 3303 address pc = base + pair->pc_offset(); 3304 if (pc > begin) { 3305 if (pc <= end) { 3306 st->move_to(column); 3307 st->print("; "); 3308 om->print_on(st); 3309 } 3310 break; 3311 } 3312 } 3313 } 3314 3315 // Print any debug info present at this pc. 3316 ScopeDesc* sd = scope_desc_in(begin, end); 3317 if (sd != NULL) { 3318 st->move_to(column); 3319 if (sd->bci() == SynchronizationEntryBCI) { 3320 st->print(";*synchronization entry"); 3321 } else { 3322 if (sd->method() == NULL) { 3323 st->print("method is NULL"); 3324 } else if (sd->method()->is_native()) { 3325 st->print("method is native"); 3326 } else { 3327 Bytecodes::Code bc = sd->method()->java_code_at(sd->bci()); 3328 st->print(";*%s", Bytecodes::name(bc)); 3329 switch (bc) { 3330 case Bytecodes::_invokevirtual: 3331 case Bytecodes::_invokespecial: 3332 case Bytecodes::_invokestatic: 3333 case Bytecodes::_invokeinterface: 3334 { 3335 Bytecode_invoke invoke(sd->method(), sd->bci()); 3336 st->print(" "); 3337 if (invoke.name() != NULL) 3338 invoke.name()->print_symbol_on(st); 3339 else 3340 st->print("<UNKNOWN>"); 3341 break; 3342 } 3343 case Bytecodes::_getfield: 3344 case Bytecodes::_putfield: 3345 case Bytecodes::_getstatic: 3346 case Bytecodes::_putstatic: 3347 { 3348 Bytecode_field field(sd->method(), sd->bci()); 3349 st->print(" "); 3350 if (field.name() != NULL) 3351 field.name()->print_symbol_on(st); 3352 else 3353 st->print("<UNKNOWN>"); 3354 } 3355 } 3356 } 3357 st->print(" {reexecute=%d rethrow=%d return_oop=%d}", sd->should_reexecute(), sd->rethrow_exception(), sd->return_oop()); 3358 } 3359 3360 // Print all scopes 3361 for (;sd != NULL; sd = sd->sender()) { 3362 st->move_to(column); 3363 st->print("; -"); 3364 if (sd->method() == NULL) { 3365 st->print("method is NULL"); 3366 } else { 3367 sd->method()->print_short_name(st); 3368 } 3369 int lineno = sd->method()->line_number_from_bci(sd->bci()); 3370 if (lineno != -1) { 3371 st->print("@%d (line %d)", sd->bci(), lineno); 3372 } else { 3373 st->print("@%d", sd->bci()); 3374 } 3375 st->cr(); 3376 } 3377 } 3378 3379 // Print relocation information 3380 const char* str = reloc_string_for(begin, end); 3381 if (str != NULL) { 3382 if (sd != NULL) st->cr(); 3383 st->move_to(column); 3384 st->print("; {%s}", str); 3385 } 3386 int cont_offset = ImplicitExceptionTable(this).at(begin - code_begin()); 3387 if (cont_offset != 0) { 3388 st->move_to(column); 3389 st->print("; implicit exception: dispatches to " INTPTR_FORMAT, p2i(code_begin() + cont_offset)); 3390 } 3391 3392 } 3393 3394 #ifndef PRODUCT 3395 3396 void nmethod::print_value_on(outputStream* st) const { 3397 st->print("nmethod"); 3398 print_on(st, NULL); 3399 } 3400 3401 void nmethod::print_calls(outputStream* st) { 3402 RelocIterator iter(this); 3403 while (iter.next()) { 3404 switch (iter.type()) { 3405 case relocInfo::virtual_call_type: 3406 case relocInfo::opt_virtual_call_type: { 3407 VerifyMutexLocker mc(CompiledIC_lock); 3408 CompiledIC_at(&iter)->print(); 3409 break; 3410 } 3411 case relocInfo::static_call_type: 3412 st->print_cr("Static call at " INTPTR_FORMAT, p2i(iter.reloc()->addr())); 3413 compiledStaticCall_at(iter.reloc())->print(); 3414 break; 3415 } 3416 } 3417 } 3418 3419 void nmethod::print_handler_table() { 3420 ExceptionHandlerTable(this).print(); 3421 } 3422 3423 void nmethod::print_nul_chk_table() { 3424 ImplicitExceptionTable(this).print(code_begin()); 3425 } 3426 3427 void nmethod::print_statistics() { 3428 ttyLocker ttyl; 3429 if (xtty != NULL) xtty->head("statistics type='nmethod'"); 3430 native_nmethod_stats.print_native_nmethod_stats(); 3431 #ifdef COMPILER1 3432 c1_java_nmethod_stats.print_nmethod_stats("C1"); 3433 #endif 3434 #ifdef COMPILER2 3435 c2_java_nmethod_stats.print_nmethod_stats("C2"); 3436 #endif 3437 #if INCLUDE_JVMCI 3438 jvmci_java_nmethod_stats.print_nmethod_stats("JVMCI"); 3439 #endif 3440 #ifdef SHARK 3441 shark_java_nmethod_stats.print_nmethod_stats("Shark"); 3442 #endif 3443 unknown_java_nmethod_stats.print_nmethod_stats("Unknown"); 3444 DebugInformationRecorder::print_statistics(); 3445 #ifndef PRODUCT 3446 pc_nmethod_stats.print_pc_stats(); 3447 #endif 3448 Dependencies::print_statistics(); 3449 if (xtty != NULL) xtty->tail("statistics"); 3450 } 3451 3452 #endif // !PRODUCT 3453 3454 #if INCLUDE_JVMCI 3455 void nmethod::clear_jvmci_installed_code() { 3456 // write_ref_method_pre/post can only be safely called at a 3457 // safepoint or while holding the CodeCache_lock 3458 assert(CodeCache_lock->is_locked() || 3459 SafepointSynchronize::is_at_safepoint(), "should be performed under a lock for consistency"); 3460 if (_jvmci_installed_code != NULL) { 3461 // This must be done carefully to maintain nmethod remembered sets properly 3462 BarrierSet* bs = Universe::heap()->barrier_set(); 3463 bs->write_ref_nmethod_pre(&_jvmci_installed_code, this); 3464 _jvmci_installed_code = NULL; 3465 bs->write_ref_nmethod_post(&_jvmci_installed_code, this); 3466 } 3467 } 3468 3469 void nmethod::maybe_invalidate_installed_code() { 3470 assert(Patching_lock->is_locked() || 3471 SafepointSynchronize::is_at_safepoint(), "should be performed under a lock for consistency"); 3472 oop installed_code = jvmci_installed_code(); 3473 if (installed_code != NULL) { 3474 nmethod* nm = (nmethod*)InstalledCode::address(installed_code); 3475 if (nm == NULL || nm != this) { 3476 // The link has been broken or the InstalledCode instance is 3477 // associated with another nmethod so do nothing. 3478 return; 3479 } 3480 if (!is_alive()) { 3481 // Break the link between nmethod and InstalledCode such that the nmethod 3482 // can subsequently be flushed safely. The link must be maintained while 3483 // the method could have live activations since invalidateInstalledCode 3484 // might want to invalidate all existing activations. 3485 InstalledCode::set_address(installed_code, 0); 3486 InstalledCode::set_entryPoint(installed_code, 0); 3487 } else if (is_not_entrant()) { 3488 // Remove the entry point so any invocation will fail but keep 3489 // the address link around that so that existing activations can 3490 // be invalidated. 3491 InstalledCode::set_entryPoint(installed_code, 0); 3492 } 3493 } 3494 } 3495 3496 void nmethod::invalidate_installed_code(Handle installedCode, TRAPS) { 3497 if (installedCode() == NULL) { 3498 THROW(vmSymbols::java_lang_NullPointerException()); 3499 } 3500 jlong nativeMethod = InstalledCode::address(installedCode); 3501 nmethod* nm = (nmethod*)nativeMethod; 3502 if (nm == NULL) { 3503 // Nothing to do 3504 return; 3505 } 3506 3507 nmethodLocker nml(nm); 3508 #ifdef ASSERT 3509 { 3510 MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag); 3511 // This relationship can only be checked safely under a lock 3512 assert(nm == NULL || !nm->is_alive() || nm->jvmci_installed_code() == installedCode(), "sanity check"); 3513 } 3514 #endif 3515 3516 if (nm->is_alive()) { 3517 // The nmethod state machinery maintains the link between the 3518 // HotSpotInstalledCode and nmethod* so as long as the nmethod appears to be 3519 // alive assume there is work to do and deoptimize the nmethod. 3520 nm->mark_for_deoptimization(); 3521 VM_Deoptimize op; 3522 VMThread::execute(&op); 3523 } 3524 3525 MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag); 3526 // Check that it's still associated with the same nmethod and break 3527 // the link if it is. 3528 if (InstalledCode::address(installedCode) == nativeMethod) { 3529 InstalledCode::set_address(installedCode, 0); 3530 } 3531 } 3532 3533 char* nmethod::jvmci_installed_code_name(char* buf, size_t buflen) { 3534 if (!this->is_compiled_by_jvmci()) { 3535 return NULL; 3536 } 3537 oop installedCode = this->jvmci_installed_code(); 3538 if (installedCode != NULL) { 3539 oop installedCodeName = NULL; 3540 if (installedCode->is_a(InstalledCode::klass())) { 3541 installedCodeName = InstalledCode::name(installedCode); 3542 } 3543 if (installedCodeName != NULL) { 3544 return java_lang_String::as_utf8_string(installedCodeName, buf, (int)buflen); 3545 } else { 3546 jio_snprintf(buf, buflen, "null"); 3547 return buf; 3548 } 3549 } 3550 jio_snprintf(buf, buflen, "noInstalledCode"); 3551 return buf; 3552 } 3553 #endif 3554 3555 Method* nmethod::attached_method(address call_instr) { 3556 assert(code_contains(call_instr), "not part of the nmethod"); 3557 RelocIterator iter(this, call_instr, call_instr + 1); 3558 while (iter.next()) { 3559 if (iter.addr() == call_instr) { 3560 switch(iter.type()) { 3561 case relocInfo::static_call_type: return iter.static_call_reloc()->method_value(); 3562 case relocInfo::opt_virtual_call_type: return iter.opt_virtual_call_reloc()->method_value(); 3563 case relocInfo::virtual_call_type: return iter.virtual_call_reloc()->method_value(); 3564 } 3565 } 3566 } 3567 return NULL; // not found 3568 } 3569 3570 Method* nmethod::attached_method_before_pc(address pc) { 3571 if (NativeCall::is_call_before(pc)) { 3572 NativeCall* ncall = nativeCall_before(pc); 3573 return attached_method(ncall->instruction_address()); 3574 } 3575 return NULL; // not a call 3576 } 3577