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