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