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