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