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