1 /* 2 * Copyright (c) 1997, 2025, 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 "asm/assembler.inline.hpp" 26 #include "code/aotCodeCache.hpp" 27 #include "code/codeCache.hpp" 28 #include "code/compiledIC.hpp" 29 #include "code/dependencies.hpp" 30 #include "code/nativeInst.hpp" 31 #include "code/nmethod.inline.hpp" 32 #include "code/relocInfo.hpp" 33 #include "code/scopeDesc.hpp" 34 #include "compiler/abstractCompiler.hpp" 35 #include "compiler/compilationLog.hpp" 36 #include "compiler/compileBroker.hpp" 37 #include "compiler/compileLog.hpp" 38 #include "compiler/compileTask.hpp" 39 #include "compiler/compilerDirectives.hpp" 40 #include "compiler/compilerOracle.hpp" 41 #include "compiler/directivesParser.hpp" 42 #include "compiler/disassembler.hpp" 43 #include "compiler/oopMap.inline.hpp" 44 #include "gc/shared/barrierSet.hpp" 45 #include "gc/shared/barrierSetNMethod.hpp" 46 #include "gc/shared/classUnloadingContext.hpp" 47 #include "gc/shared/collectedHeap.hpp" 48 #include "interpreter/bytecode.inline.hpp" 49 #include "jvm.h" 50 #include "logging/log.hpp" 51 #include "logging/logStream.hpp" 52 #include "memory/allocation.inline.hpp" 53 #include "memory/resourceArea.hpp" 54 #include "memory/universe.hpp" 55 #include "oops/access.inline.hpp" 56 #include "oops/klass.inline.hpp" 57 #include "oops/method.inline.hpp" 58 #include "oops/methodData.hpp" 59 #include "oops/oop.inline.hpp" 60 #include "oops/weakHandle.inline.hpp" 61 #include "prims/jvmtiImpl.hpp" 62 #include "prims/jvmtiThreadState.hpp" 63 #include "prims/methodHandles.hpp" 64 #include "runtime/continuation.hpp" 65 #include "runtime/atomic.hpp" 66 #include "runtime/deoptimization.hpp" 67 #include "runtime/flags/flagSetting.hpp" 68 #include "runtime/frame.inline.hpp" 69 #include "runtime/handles.inline.hpp" 70 #include "runtime/jniHandles.inline.hpp" 71 #include "runtime/orderAccess.hpp" 72 #include "runtime/os.hpp" 73 #include "runtime/safepointVerifiers.hpp" 74 #include "runtime/serviceThread.hpp" 75 #include "runtime/sharedRuntime.hpp" 76 #include "runtime/signature.hpp" 77 #include "runtime/threadWXSetters.inline.hpp" 78 #include "runtime/vmThread.hpp" 79 #include "utilities/align.hpp" 80 #include "utilities/copy.hpp" 81 #include "utilities/dtrace.hpp" 82 #include "utilities/events.hpp" 83 #include "utilities/globalDefinitions.hpp" 84 #include "utilities/resourceHash.hpp" 85 #include "utilities/xmlstream.hpp" 86 #if INCLUDE_JVMCI 87 #include "jvmci/jvmciRuntime.hpp" 88 #endif 89 90 #ifdef DTRACE_ENABLED 91 92 // Only bother with this argument setup if dtrace is available 93 94 #define DTRACE_METHOD_UNLOAD_PROBE(method) \ 95 { \ 96 Method* m = (method); \ 97 if (m != nullptr) { \ 98 Symbol* klass_name = m->klass_name(); \ 99 Symbol* name = m->name(); \ 100 Symbol* signature = m->signature(); \ 101 HOTSPOT_COMPILED_METHOD_UNLOAD( \ 102 (char *) klass_name->bytes(), klass_name->utf8_length(), \ 103 (char *) name->bytes(), name->utf8_length(), \ 104 (char *) signature->bytes(), signature->utf8_length()); \ 105 } \ 106 } 107 108 #else // ndef DTRACE_ENABLED 109 110 #define DTRACE_METHOD_UNLOAD_PROBE(method) 111 112 #endif 113 114 // Cast from int value to narrow type 115 #define CHECKED_CAST(result, T, thing) \ 116 result = static_cast<T>(thing); \ 117 guarantee(static_cast<int>(result) == thing, "failed: %d != %d", static_cast<int>(result), thing); 118 119 //--------------------------------------------------------------------------------- 120 // NMethod statistics 121 // They are printed under various flags, including: 122 // PrintC1Statistics, PrintOptoStatistics, LogVMOutput, and LogCompilation. 123 // (In the latter two cases, they like other stats are printed to the log only.) 124 125 #ifndef PRODUCT 126 // These variables are put into one block to reduce relocations 127 // and make it simpler to print from the debugger. 128 struct java_nmethod_stats_struct { 129 uint nmethod_count; 130 uint total_nm_size; 131 uint total_immut_size; 132 uint total_mut_size; 133 uint relocation_size; 134 uint consts_size; 135 uint insts_size; 136 uint stub_size; 137 uint oops_size; 138 uint metadata_size; 139 uint dependencies_size; 140 uint nul_chk_table_size; 141 uint handler_table_size; 142 uint scopes_pcs_size; 143 uint scopes_data_size; 144 #if INCLUDE_JVMCI 145 uint speculations_size; 146 uint jvmci_data_size; 147 #endif 148 149 void note_nmethod(nmethod* nm) { 150 nmethod_count += 1; 151 total_nm_size += nm->size(); 152 total_immut_size += nm->immutable_data_size(); 153 total_mut_size += nm->mutable_data_size(); 154 relocation_size += nm->relocation_size(); 155 consts_size += nm->consts_size(); 156 insts_size += nm->insts_size(); 157 stub_size += nm->stub_size(); 158 oops_size += nm->oops_size(); 159 metadata_size += nm->metadata_size(); 160 scopes_data_size += nm->scopes_data_size(); 161 scopes_pcs_size += nm->scopes_pcs_size(); 162 dependencies_size += nm->dependencies_size(); 163 handler_table_size += nm->handler_table_size(); 164 nul_chk_table_size += nm->nul_chk_table_size(); 165 #if INCLUDE_JVMCI 166 speculations_size += nm->speculations_size(); 167 jvmci_data_size += nm->jvmci_data_size(); 168 #endif 169 } 170 void print_nmethod_stats(const char* name) { 171 if (nmethod_count == 0) return; 172 tty->print_cr("Statistics for %u bytecoded nmethods for %s:", nmethod_count, name); 173 uint total_size = total_nm_size + total_immut_size + total_mut_size; 174 if (total_nm_size != 0) { 175 tty->print_cr(" total size = %u (100%%)", total_size); 176 tty->print_cr(" in CodeCache = %u (%f%%)", total_nm_size, (total_nm_size * 100.0f)/total_size); 177 } 178 uint header_size = (uint)(nmethod_count * sizeof(nmethod)); 179 if (nmethod_count != 0) { 180 tty->print_cr(" header = %u (%f%%)", header_size, (header_size * 100.0f)/total_nm_size); 181 } 182 if (consts_size != 0) { 183 tty->print_cr(" constants = %u (%f%%)", consts_size, (consts_size * 100.0f)/total_nm_size); 184 } 185 if (insts_size != 0) { 186 tty->print_cr(" main code = %u (%f%%)", insts_size, (insts_size * 100.0f)/total_nm_size); 187 } 188 if (stub_size != 0) { 189 tty->print_cr(" stub code = %u (%f%%)", stub_size, (stub_size * 100.0f)/total_nm_size); 190 } 191 if (oops_size != 0) { 192 tty->print_cr(" oops = %u (%f%%)", oops_size, (oops_size * 100.0f)/total_nm_size); 193 } 194 if (total_mut_size != 0) { 195 tty->print_cr(" mutable data = %u (%f%%)", total_mut_size, (total_mut_size * 100.0f)/total_size); 196 } 197 if (relocation_size != 0) { 198 tty->print_cr(" relocation = %u (%f%%)", relocation_size, (relocation_size * 100.0f)/total_mut_size); 199 } 200 if (metadata_size != 0) { 201 tty->print_cr(" metadata = %u (%f%%)", metadata_size, (metadata_size * 100.0f)/total_mut_size); 202 } 203 #if INCLUDE_JVMCI 204 if (jvmci_data_size != 0) { 205 tty->print_cr(" JVMCI data = %u (%f%%)", jvmci_data_size, (jvmci_data_size * 100.0f)/total_mut_size); 206 } 207 #endif 208 if (total_immut_size != 0) { 209 tty->print_cr(" immutable data = %u (%f%%)", total_immut_size, (total_immut_size * 100.0f)/total_size); 210 } 211 if (dependencies_size != 0) { 212 tty->print_cr(" dependencies = %u (%f%%)", dependencies_size, (dependencies_size * 100.0f)/total_immut_size); 213 } 214 if (nul_chk_table_size != 0) { 215 tty->print_cr(" nul chk table = %u (%f%%)", nul_chk_table_size, (nul_chk_table_size * 100.0f)/total_immut_size); 216 } 217 if (handler_table_size != 0) { 218 tty->print_cr(" handler table = %u (%f%%)", handler_table_size, (handler_table_size * 100.0f)/total_immut_size); 219 } 220 if (scopes_pcs_size != 0) { 221 tty->print_cr(" scopes pcs = %u (%f%%)", scopes_pcs_size, (scopes_pcs_size * 100.0f)/total_immut_size); 222 } 223 if (scopes_data_size != 0) { 224 tty->print_cr(" scopes data = %u (%f%%)", scopes_data_size, (scopes_data_size * 100.0f)/total_immut_size); 225 } 226 #if INCLUDE_JVMCI 227 if (speculations_size != 0) { 228 tty->print_cr(" speculations = %u (%f%%)", speculations_size, (speculations_size * 100.0f)/total_immut_size); 229 } 230 #endif 231 } 232 }; 233 234 struct native_nmethod_stats_struct { 235 uint native_nmethod_count; 236 uint native_total_size; 237 uint native_relocation_size; 238 uint native_insts_size; 239 uint native_oops_size; 240 uint native_metadata_size; 241 void note_native_nmethod(nmethod* nm) { 242 native_nmethod_count += 1; 243 native_total_size += nm->size(); 244 native_relocation_size += nm->relocation_size(); 245 native_insts_size += nm->insts_size(); 246 native_oops_size += nm->oops_size(); 247 native_metadata_size += nm->metadata_size(); 248 } 249 void print_native_nmethod_stats() { 250 if (native_nmethod_count == 0) return; 251 tty->print_cr("Statistics for %u native nmethods:", native_nmethod_count); 252 if (native_total_size != 0) tty->print_cr(" N. total size = %u", native_total_size); 253 if (native_relocation_size != 0) tty->print_cr(" N. relocation = %u", native_relocation_size); 254 if (native_insts_size != 0) tty->print_cr(" N. main code = %u", native_insts_size); 255 if (native_oops_size != 0) tty->print_cr(" N. oops = %u", native_oops_size); 256 if (native_metadata_size != 0) tty->print_cr(" N. metadata = %u", native_metadata_size); 257 } 258 }; 259 260 struct pc_nmethod_stats_struct { 261 uint pc_desc_init; // number of initialization of cache (= number of caches) 262 uint pc_desc_queries; // queries to nmethod::find_pc_desc 263 uint pc_desc_approx; // number of those which have approximate true 264 uint pc_desc_repeats; // number of _pc_descs[0] hits 265 uint pc_desc_hits; // number of LRU cache hits 266 uint pc_desc_tests; // total number of PcDesc examinations 267 uint pc_desc_searches; // total number of quasi-binary search steps 268 uint pc_desc_adds; // number of LUR cache insertions 269 270 void print_pc_stats() { 271 tty->print_cr("PcDesc Statistics: %u queries, %.2f comparisons per query", 272 pc_desc_queries, 273 (double)(pc_desc_tests + pc_desc_searches) 274 / pc_desc_queries); 275 tty->print_cr(" caches=%d queries=%u/%u, hits=%u+%u, tests=%u+%u, adds=%u", 276 pc_desc_init, 277 pc_desc_queries, pc_desc_approx, 278 pc_desc_repeats, pc_desc_hits, 279 pc_desc_tests, pc_desc_searches, pc_desc_adds); 280 } 281 }; 282 283 #ifdef COMPILER1 284 static java_nmethod_stats_struct c1_java_nmethod_stats; 285 #endif 286 #ifdef COMPILER2 287 static java_nmethod_stats_struct c2_java_nmethod_stats; 288 #endif 289 #if INCLUDE_JVMCI 290 static java_nmethod_stats_struct jvmci_java_nmethod_stats; 291 #endif 292 static java_nmethod_stats_struct unknown_java_nmethod_stats; 293 294 static native_nmethod_stats_struct native_nmethod_stats; 295 static pc_nmethod_stats_struct pc_nmethod_stats; 296 297 static void note_java_nmethod(nmethod* nm) { 298 #ifdef COMPILER1 299 if (nm->is_compiled_by_c1()) { 300 c1_java_nmethod_stats.note_nmethod(nm); 301 } else 302 #endif 303 #ifdef COMPILER2 304 if (nm->is_compiled_by_c2()) { 305 c2_java_nmethod_stats.note_nmethod(nm); 306 } else 307 #endif 308 #if INCLUDE_JVMCI 309 if (nm->is_compiled_by_jvmci()) { 310 jvmci_java_nmethod_stats.note_nmethod(nm); 311 } else 312 #endif 313 { 314 unknown_java_nmethod_stats.note_nmethod(nm); 315 } 316 } 317 #endif // !PRODUCT 318 319 //--------------------------------------------------------------------------------- 320 321 322 ExceptionCache::ExceptionCache(Handle exception, address pc, address handler) { 323 assert(pc != nullptr, "Must be non null"); 324 assert(exception.not_null(), "Must be non null"); 325 assert(handler != nullptr, "Must be non null"); 326 327 _count = 0; 328 _exception_type = exception->klass(); 329 _next = nullptr; 330 _purge_list_next = nullptr; 331 332 add_address_and_handler(pc,handler); 333 } 334 335 336 address ExceptionCache::match(Handle exception, address pc) { 337 assert(pc != nullptr,"Must be non null"); 338 assert(exception.not_null(),"Must be non null"); 339 if (exception->klass() == exception_type()) { 340 return (test_address(pc)); 341 } 342 343 return nullptr; 344 } 345 346 347 bool ExceptionCache::match_exception_with_space(Handle exception) { 348 assert(exception.not_null(),"Must be non null"); 349 if (exception->klass() == exception_type() && count() < cache_size) { 350 return true; 351 } 352 return false; 353 } 354 355 356 address ExceptionCache::test_address(address addr) { 357 int limit = count(); 358 for (int i = 0; i < limit; i++) { 359 if (pc_at(i) == addr) { 360 return handler_at(i); 361 } 362 } 363 return nullptr; 364 } 365 366 367 bool ExceptionCache::add_address_and_handler(address addr, address handler) { 368 if (test_address(addr) == handler) return true; 369 370 int index = count(); 371 if (index < cache_size) { 372 set_pc_at(index, addr); 373 set_handler_at(index, handler); 374 increment_count(); 375 return true; 376 } 377 return false; 378 } 379 380 ExceptionCache* ExceptionCache::next() { 381 return Atomic::load(&_next); 382 } 383 384 void ExceptionCache::set_next(ExceptionCache *ec) { 385 Atomic::store(&_next, ec); 386 } 387 388 //----------------------------------------------------------------------------- 389 390 391 // Helper used by both find_pc_desc methods. 392 static inline bool match_desc(PcDesc* pc, int pc_offset, bool approximate) { 393 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_tests); 394 if (!approximate) { 395 return pc->pc_offset() == pc_offset; 396 } else { 397 // Do not look before the sentinel 398 assert(pc_offset > PcDesc::lower_offset_limit, "illegal pc_offset"); 399 return pc_offset <= pc->pc_offset() && (pc-1)->pc_offset() < pc_offset; 400 } 401 } 402 403 void PcDescCache::init_to(PcDesc* initial_pc_desc) { 404 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_init); 405 // initialize the cache by filling it with benign (non-null) values 406 assert(initial_pc_desc != nullptr && initial_pc_desc->pc_offset() == PcDesc::lower_offset_limit, 407 "must start with a sentinel"); 408 for (int i = 0; i < cache_size; i++) { 409 _pc_descs[i] = initial_pc_desc; 410 } 411 } 412 413 PcDesc* PcDescCache::find_pc_desc(int pc_offset, bool approximate) { 414 // Note: one might think that caching the most recently 415 // read value separately would be a win, but one would be 416 // wrong. When many threads are updating it, the cache 417 // line it's in would bounce between caches, negating 418 // any benefit. 419 420 // In order to prevent race conditions do not load cache elements 421 // repeatedly, but use a local copy: 422 PcDesc* res; 423 424 // Step one: Check the most recently added value. 425 res = _pc_descs[0]; 426 assert(res != nullptr, "PcDesc cache should be initialized already"); 427 428 // Approximate only here since PcDescContainer::find_pc_desc() checked for exact case. 429 if (approximate && match_desc(res, pc_offset, approximate)) { 430 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_repeats); 431 return res; 432 } 433 434 // Step two: Check the rest of the LRU cache. 435 for (int i = 1; i < cache_size; ++i) { 436 res = _pc_descs[i]; 437 if (res->pc_offset() < 0) break; // optimization: skip empty cache 438 if (match_desc(res, pc_offset, approximate)) { 439 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_hits); 440 return res; 441 } 442 } 443 444 // Report failure. 445 return nullptr; 446 } 447 448 void PcDescCache::add_pc_desc(PcDesc* pc_desc) { 449 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_adds); 450 // Update the LRU cache by shifting pc_desc forward. 451 for (int i = 0; i < cache_size; i++) { 452 PcDesc* next = _pc_descs[i]; 453 _pc_descs[i] = pc_desc; 454 pc_desc = next; 455 } 456 } 457 458 // adjust pcs_size so that it is a multiple of both oopSize and 459 // sizeof(PcDesc) (assumes that if sizeof(PcDesc) is not a multiple 460 // of oopSize, then 2*sizeof(PcDesc) is) 461 static int adjust_pcs_size(int pcs_size) { 462 int nsize = align_up(pcs_size, oopSize); 463 if ((nsize % sizeof(PcDesc)) != 0) { 464 nsize = pcs_size + sizeof(PcDesc); 465 } 466 assert((nsize % oopSize) == 0, "correct alignment"); 467 return nsize; 468 } 469 470 bool nmethod::is_method_handle_return(address return_pc) { 471 if (!has_method_handle_invokes()) return false; 472 PcDesc* pd = pc_desc_at(return_pc); 473 if (pd == nullptr) 474 return false; 475 return pd->is_method_handle_invoke(); 476 } 477 478 // Returns a string version of the method state. 479 const char* nmethod::state() const { 480 int state = get_state(); 481 switch (state) { 482 case not_installed: 483 return "not installed"; 484 case in_use: 485 return "in use"; 486 case not_entrant: 487 return "not_entrant"; 488 default: 489 fatal("unexpected method state: %d", state); 490 return nullptr; 491 } 492 } 493 494 void nmethod::set_deoptimized_done() { 495 ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag); 496 if (_deoptimization_status != deoptimize_done) { // can't go backwards 497 Atomic::store(&_deoptimization_status, deoptimize_done); 498 } 499 } 500 501 ExceptionCache* nmethod::exception_cache_acquire() const { 502 return Atomic::load_acquire(&_exception_cache); 503 } 504 505 void nmethod::add_exception_cache_entry(ExceptionCache* new_entry) { 506 assert(ExceptionCache_lock->owned_by_self(),"Must hold the ExceptionCache_lock"); 507 assert(new_entry != nullptr,"Must be non null"); 508 assert(new_entry->next() == nullptr, "Must be null"); 509 510 for (;;) { 511 ExceptionCache *ec = exception_cache(); 512 if (ec != nullptr) { 513 Klass* ex_klass = ec->exception_type(); 514 if (!ex_klass->is_loader_alive()) { 515 // We must guarantee that entries are not inserted with new next pointer 516 // edges to ExceptionCache entries with dead klasses, due to bad interactions 517 // with concurrent ExceptionCache cleanup. Therefore, the inserts roll 518 // the head pointer forward to the first live ExceptionCache, so that the new 519 // next pointers always point at live ExceptionCaches, that are not removed due 520 // to concurrent ExceptionCache cleanup. 521 ExceptionCache* next = ec->next(); 522 if (Atomic::cmpxchg(&_exception_cache, ec, next) == ec) { 523 CodeCache::release_exception_cache(ec); 524 } 525 continue; 526 } 527 ec = exception_cache(); 528 if (ec != nullptr) { 529 new_entry->set_next(ec); 530 } 531 } 532 if (Atomic::cmpxchg(&_exception_cache, ec, new_entry) == ec) { 533 return; 534 } 535 } 536 } 537 538 void nmethod::clean_exception_cache() { 539 // For each nmethod, only a single thread may call this cleanup function 540 // at the same time, whether called in STW cleanup or concurrent cleanup. 541 // Note that if the GC is processing exception cache cleaning in a concurrent phase, 542 // then a single writer may contend with cleaning up the head pointer to the 543 // first ExceptionCache node that has a Klass* that is alive. That is fine, 544 // as long as there is no concurrent cleanup of next pointers from concurrent writers. 545 // And the concurrent writers do not clean up next pointers, only the head. 546 // Also note that concurrent readers will walk through Klass* pointers that are not 547 // alive. That does not cause ABA problems, because Klass* is deleted after 548 // a handshake with all threads, after all stale ExceptionCaches have been 549 // unlinked. That is also when the CodeCache::exception_cache_purge_list() 550 // is deleted, with all ExceptionCache entries that were cleaned concurrently. 551 // That similarly implies that CAS operations on ExceptionCache entries do not 552 // suffer from ABA problems as unlinking and deletion is separated by a global 553 // handshake operation. 554 ExceptionCache* prev = nullptr; 555 ExceptionCache* curr = exception_cache_acquire(); 556 557 while (curr != nullptr) { 558 ExceptionCache* next = curr->next(); 559 560 if (!curr->exception_type()->is_loader_alive()) { 561 if (prev == nullptr) { 562 // Try to clean head; this is contended by concurrent inserts, that 563 // both lazily clean the head, and insert entries at the head. If 564 // the CAS fails, the operation is restarted. 565 if (Atomic::cmpxchg(&_exception_cache, curr, next) != curr) { 566 prev = nullptr; 567 curr = exception_cache_acquire(); 568 continue; 569 } 570 } else { 571 // It is impossible to during cleanup connect the next pointer to 572 // an ExceptionCache that has not been published before a safepoint 573 // prior to the cleanup. Therefore, release is not required. 574 prev->set_next(next); 575 } 576 // prev stays the same. 577 578 CodeCache::release_exception_cache(curr); 579 } else { 580 prev = curr; 581 } 582 583 curr = next; 584 } 585 } 586 587 // public method for accessing the exception cache 588 // These are the public access methods. 589 address nmethod::handler_for_exception_and_pc(Handle exception, address pc) { 590 // We never grab a lock to read the exception cache, so we may 591 // have false negatives. This is okay, as it can only happen during 592 // the first few exception lookups for a given nmethod. 593 ExceptionCache* ec = exception_cache_acquire(); 594 while (ec != nullptr) { 595 address ret_val; 596 if ((ret_val = ec->match(exception,pc)) != nullptr) { 597 return ret_val; 598 } 599 ec = ec->next(); 600 } 601 return nullptr; 602 } 603 604 void nmethod::add_handler_for_exception_and_pc(Handle exception, address pc, address handler) { 605 // There are potential race conditions during exception cache updates, so we 606 // must own the ExceptionCache_lock before doing ANY modifications. Because 607 // we don't lock during reads, it is possible to have several threads attempt 608 // to update the cache with the same data. We need to check for already inserted 609 // copies of the current data before adding it. 610 611 MutexLocker ml(ExceptionCache_lock); 612 ExceptionCache* target_entry = exception_cache_entry_for_exception(exception); 613 614 if (target_entry == nullptr || !target_entry->add_address_and_handler(pc,handler)) { 615 target_entry = new ExceptionCache(exception,pc,handler); 616 add_exception_cache_entry(target_entry); 617 } 618 } 619 620 // private method for handling exception cache 621 // These methods are private, and used to manipulate the exception cache 622 // directly. 623 ExceptionCache* nmethod::exception_cache_entry_for_exception(Handle exception) { 624 ExceptionCache* ec = exception_cache_acquire(); 625 while (ec != nullptr) { 626 if (ec->match_exception_with_space(exception)) { 627 return ec; 628 } 629 ec = ec->next(); 630 } 631 return nullptr; 632 } 633 634 bool nmethod::is_at_poll_return(address pc) { 635 RelocIterator iter(this, pc, pc+1); 636 while (iter.next()) { 637 if (iter.type() == relocInfo::poll_return_type) 638 return true; 639 } 640 return false; 641 } 642 643 644 bool nmethod::is_at_poll_or_poll_return(address pc) { 645 RelocIterator iter(this, pc, pc+1); 646 while (iter.next()) { 647 relocInfo::relocType t = iter.type(); 648 if (t == relocInfo::poll_return_type || t == relocInfo::poll_type) 649 return true; 650 } 651 return false; 652 } 653 654 void nmethod::verify_oop_relocations() { 655 // Ensure sure that the code matches the current oop values 656 RelocIterator iter(this, nullptr, nullptr); 657 while (iter.next()) { 658 if (iter.type() == relocInfo::oop_type) { 659 oop_Relocation* reloc = iter.oop_reloc(); 660 if (!reloc->oop_is_immediate()) { 661 reloc->verify_oop_relocation(); 662 } 663 } 664 } 665 } 666 667 668 ScopeDesc* nmethod::scope_desc_at(address pc) { 669 PcDesc* pd = pc_desc_at(pc); 670 guarantee(pd != nullptr, "scope must be present"); 671 return new ScopeDesc(this, pd); 672 } 673 674 ScopeDesc* nmethod::scope_desc_near(address pc) { 675 PcDesc* pd = pc_desc_near(pc); 676 guarantee(pd != nullptr, "scope must be present"); 677 return new ScopeDesc(this, pd); 678 } 679 680 address nmethod::oops_reloc_begin() const { 681 // If the method is not entrant then a JMP is plastered over the 682 // first few bytes. If an oop in the old code was there, that oop 683 // should not get GC'd. Skip the first few bytes of oops on 684 // not-entrant methods. 685 if (frame_complete_offset() != CodeOffsets::frame_never_safe && 686 code_begin() + frame_complete_offset() > 687 verified_entry_point() + NativeJump::instruction_size) 688 { 689 // If we have a frame_complete_offset after the native jump, then there 690 // is no point trying to look for oops before that. This is a requirement 691 // for being allowed to scan oops concurrently. 692 return code_begin() + frame_complete_offset(); 693 } 694 695 address low_boundary = verified_entry_point(); 696 if (!is_in_use()) { 697 low_boundary += NativeJump::instruction_size; 698 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump. 699 // This means that the low_boundary is going to be a little too high. 700 // This shouldn't matter, since oops of non-entrant methods are never used. 701 // In fact, why are we bothering to look at oops in a non-entrant method?? 702 } 703 return low_boundary; 704 } 705 706 // Method that knows how to preserve outgoing arguments at call. This method must be 707 // called with a frame corresponding to a Java invoke 708 void nmethod::preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f) { 709 if (method() == nullptr) { 710 return; 711 } 712 713 // handle the case of an anchor explicitly set in continuation code that doesn't have a callee 714 JavaThread* thread = reg_map->thread(); 715 if ((thread->has_last_Java_frame() && fr.sp() == thread->last_Java_sp()) 716 JVMTI_ONLY(|| (method()->is_continuation_enter_intrinsic() && thread->on_monitor_waited_event()))) { 717 return; 718 } 719 720 if (!method()->is_native()) { 721 address pc = fr.pc(); 722 bool has_receiver, has_appendix; 723 Symbol* signature; 724 725 // The method attached by JIT-compilers should be used, if present. 726 // Bytecode can be inaccurate in such case. 727 Method* callee = attached_method_before_pc(pc); 728 if (callee != nullptr) { 729 has_receiver = !(callee->access_flags().is_static()); 730 has_appendix = false; 731 signature = callee->signature(); 732 } else { 733 SimpleScopeDesc ssd(this, pc); 734 735 Bytecode_invoke call(methodHandle(Thread::current(), ssd.method()), ssd.bci()); 736 has_receiver = call.has_receiver(); 737 has_appendix = call.has_appendix(); 738 signature = call.signature(); 739 } 740 741 fr.oops_compiled_arguments_do(signature, has_receiver, has_appendix, reg_map, f); 742 } else if (method()->is_continuation_enter_intrinsic()) { 743 // This method only calls Continuation.enter() 744 Symbol* signature = vmSymbols::continuationEnter_signature(); 745 fr.oops_compiled_arguments_do(signature, false, false, reg_map, f); 746 } 747 } 748 749 Method* nmethod::attached_method(address call_instr) { 750 assert(code_contains(call_instr), "not part of the nmethod"); 751 RelocIterator iter(this, call_instr, call_instr + 1); 752 while (iter.next()) { 753 if (iter.addr() == call_instr) { 754 switch(iter.type()) { 755 case relocInfo::static_call_type: return iter.static_call_reloc()->method_value(); 756 case relocInfo::opt_virtual_call_type: return iter.opt_virtual_call_reloc()->method_value(); 757 case relocInfo::virtual_call_type: return iter.virtual_call_reloc()->method_value(); 758 default: break; 759 } 760 } 761 } 762 return nullptr; // not found 763 } 764 765 Method* nmethod::attached_method_before_pc(address pc) { 766 if (NativeCall::is_call_before(pc)) { 767 NativeCall* ncall = nativeCall_before(pc); 768 return attached_method(ncall->instruction_address()); 769 } 770 return nullptr; // not a call 771 } 772 773 void nmethod::clear_inline_caches() { 774 assert(SafepointSynchronize::is_at_safepoint(), "clearing of IC's only allowed at safepoint"); 775 RelocIterator iter(this); 776 while (iter.next()) { 777 iter.reloc()->clear_inline_cache(); 778 } 779 } 780 781 #ifdef ASSERT 782 // Check class_loader is alive for this bit of metadata. 783 class CheckClass : public MetadataClosure { 784 void do_metadata(Metadata* md) { 785 Klass* klass = nullptr; 786 if (md->is_klass()) { 787 klass = ((Klass*)md); 788 } else if (md->is_method()) { 789 klass = ((Method*)md)->method_holder(); 790 } else if (md->is_methodData()) { 791 klass = ((MethodData*)md)->method()->method_holder(); 792 } else if (md->is_methodCounters()) { 793 klass = ((MethodCounters*)md)->method()->method_holder(); 794 } else { 795 md->print(); 796 ShouldNotReachHere(); 797 } 798 assert(klass->is_loader_alive(), "must be alive"); 799 } 800 }; 801 #endif // ASSERT 802 803 804 static void clean_ic_if_metadata_is_dead(CompiledIC *ic) { 805 ic->clean_metadata(); 806 } 807 808 // Clean references to unloaded nmethods at addr from this one, which is not unloaded. 809 template <typename CallsiteT> 810 static void clean_if_nmethod_is_unloaded(CallsiteT* callsite, nmethod* from, 811 bool clean_all) { 812 CodeBlob* cb = CodeCache::find_blob(callsite->destination()); 813 if (!cb->is_nmethod()) { 814 return; 815 } 816 nmethod* nm = cb->as_nmethod(); 817 if (clean_all || !nm->is_in_use() || nm->is_unloading() || nm->method()->code() != nm) { 818 callsite->set_to_clean(); 819 } 820 } 821 822 // Cleans caches in nmethods that point to either classes that are unloaded 823 // or nmethods that are unloaded. 824 // 825 // Can be called either in parallel by G1 currently or after all 826 // nmethods are unloaded. Return postponed=true in the parallel case for 827 // inline caches found that point to nmethods that are not yet visited during 828 // the do_unloading walk. 829 void nmethod::unload_nmethod_caches(bool unloading_occurred) { 830 ResourceMark rm; 831 832 // Exception cache only needs to be called if unloading occurred 833 if (unloading_occurred) { 834 clean_exception_cache(); 835 } 836 837 cleanup_inline_caches_impl(unloading_occurred, false); 838 839 #ifdef ASSERT 840 // Check that the metadata embedded in the nmethod is alive 841 CheckClass check_class; 842 metadata_do(&check_class); 843 #endif 844 } 845 846 void nmethod::run_nmethod_entry_barrier() { 847 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod(); 848 if (bs_nm != nullptr) { 849 // We want to keep an invariant that nmethods found through iterations of a Thread's 850 // nmethods found in safepoints have gone through an entry barrier and are not armed. 851 // By calling this nmethod entry barrier, it plays along and acts 852 // like any other nmethod found on the stack of a thread (fewer surprises). 853 nmethod* nm = this; 854 bool alive = bs_nm->nmethod_entry_barrier(nm); 855 assert(alive, "should be alive"); 856 } 857 } 858 859 // Only called by whitebox test 860 void nmethod::cleanup_inline_caches_whitebox() { 861 assert_locked_or_safepoint(CodeCache_lock); 862 CompiledICLocker ic_locker(this); 863 cleanup_inline_caches_impl(false /* unloading_occurred */, true /* clean_all */); 864 } 865 866 address* nmethod::orig_pc_addr(const frame* fr) { 867 return (address*) ((address)fr->unextended_sp() + orig_pc_offset()); 868 } 869 870 // Called to clean up after class unloading for live nmethods 871 void nmethod::cleanup_inline_caches_impl(bool unloading_occurred, bool clean_all) { 872 assert(CompiledICLocker::is_safe(this), "mt unsafe call"); 873 ResourceMark rm; 874 875 // Find all calls in an nmethod and clear the ones that point to bad nmethods. 876 RelocIterator iter(this, oops_reloc_begin()); 877 bool is_in_static_stub = false; 878 while(iter.next()) { 879 880 switch (iter.type()) { 881 882 case relocInfo::virtual_call_type: 883 if (unloading_occurred) { 884 // If class unloading occurred we first clear ICs where the cached metadata 885 // is referring to an unloaded klass or method. 886 clean_ic_if_metadata_is_dead(CompiledIC_at(&iter)); 887 } 888 889 clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), this, clean_all); 890 break; 891 892 case relocInfo::opt_virtual_call_type: 893 case relocInfo::static_call_type: 894 clean_if_nmethod_is_unloaded(CompiledDirectCall::at(iter.reloc()), this, clean_all); 895 break; 896 897 case relocInfo::static_stub_type: { 898 is_in_static_stub = true; 899 break; 900 } 901 902 case relocInfo::metadata_type: { 903 // Only the metadata relocations contained in static/opt virtual call stubs 904 // contains the Method* passed to c2i adapters. It is the only metadata 905 // relocation that needs to be walked, as it is the one metadata relocation 906 // that violates the invariant that all metadata relocations have an oop 907 // in the compiled method (due to deferred resolution and code patching). 908 909 // This causes dead metadata to remain in compiled methods that are not 910 // unloading. Unless these slippery metadata relocations of the static 911 // stubs are at least cleared, subsequent class redefinition operations 912 // will access potentially free memory, and JavaThread execution 913 // concurrent to class unloading may call c2i adapters with dead methods. 914 if (!is_in_static_stub) { 915 // The first metadata relocation after a static stub relocation is the 916 // metadata relocation of the static stub used to pass the Method* to 917 // c2i adapters. 918 continue; 919 } 920 is_in_static_stub = false; 921 if (is_unloading()) { 922 // If the nmethod itself is dying, then it may point at dead metadata. 923 // Nobody should follow that metadata; it is strictly unsafe. 924 continue; 925 } 926 metadata_Relocation* r = iter.metadata_reloc(); 927 Metadata* md = r->metadata_value(); 928 if (md != nullptr && md->is_method()) { 929 Method* method = static_cast<Method*>(md); 930 if (!method->method_holder()->is_loader_alive()) { 931 Atomic::store(r->metadata_addr(), (Method*)nullptr); 932 933 if (!r->metadata_is_immediate()) { 934 r->fix_metadata_relocation(); 935 } 936 } 937 } 938 break; 939 } 940 941 default: 942 break; 943 } 944 } 945 } 946 947 address nmethod::continuation_for_implicit_exception(address pc, bool for_div0_check) { 948 // Exception happened outside inline-cache check code => we are inside 949 // an active nmethod => use cpc to determine a return address 950 int exception_offset = int(pc - code_begin()); 951 int cont_offset = ImplicitExceptionTable(this).continuation_offset( exception_offset ); 952 #ifdef ASSERT 953 if (cont_offset == 0) { 954 Thread* thread = Thread::current(); 955 ResourceMark rm(thread); 956 CodeBlob* cb = CodeCache::find_blob(pc); 957 assert(cb != nullptr && cb == this, ""); 958 959 // Keep tty output consistent. To avoid ttyLocker, we buffer in stream, and print all at once. 960 stringStream ss; 961 ss.print_cr("implicit exception happened at " INTPTR_FORMAT, p2i(pc)); 962 print_on(&ss); 963 method()->print_codes_on(&ss); 964 print_code_on(&ss); 965 print_pcs_on(&ss); 966 tty->print("%s", ss.as_string()); // print all at once 967 } 968 #endif 969 if (cont_offset == 0) { 970 // Let the normal error handling report the exception 971 return nullptr; 972 } 973 if (cont_offset == exception_offset) { 974 #if INCLUDE_JVMCI 975 Deoptimization::DeoptReason deopt_reason = for_div0_check ? Deoptimization::Reason_div0_check : Deoptimization::Reason_null_check; 976 JavaThread *thread = JavaThread::current(); 977 thread->set_jvmci_implicit_exception_pc(pc); 978 thread->set_pending_deoptimization(Deoptimization::make_trap_request(deopt_reason, 979 Deoptimization::Action_reinterpret)); 980 return (SharedRuntime::deopt_blob()->implicit_exception_uncommon_trap()); 981 #else 982 ShouldNotReachHere(); 983 #endif 984 } 985 return code_begin() + cont_offset; 986 } 987 988 class HasEvolDependency : public MetadataClosure { 989 bool _has_evol_dependency; 990 public: 991 HasEvolDependency() : _has_evol_dependency(false) {} 992 void do_metadata(Metadata* md) { 993 if (md->is_method()) { 994 Method* method = (Method*)md; 995 if (method->is_old()) { 996 _has_evol_dependency = true; 997 } 998 } 999 } 1000 bool has_evol_dependency() const { return _has_evol_dependency; } 1001 }; 1002 1003 bool nmethod::has_evol_metadata() { 1004 // Check the metadata in relocIter and CompiledIC and also deoptimize 1005 // any nmethod that has reference to old methods. 1006 HasEvolDependency check_evol; 1007 metadata_do(&check_evol); 1008 if (check_evol.has_evol_dependency() && log_is_enabled(Debug, redefine, class, nmethod)) { 1009 ResourceMark rm; 1010 log_debug(redefine, class, nmethod) 1011 ("Found evol dependency of nmethod %s.%s(%s) compile_id=%d on in nmethod metadata", 1012 _method->method_holder()->external_name(), 1013 _method->name()->as_C_string(), 1014 _method->signature()->as_C_string(), 1015 compile_id()); 1016 } 1017 return check_evol.has_evol_dependency(); 1018 } 1019 1020 int nmethod::total_size() const { 1021 return 1022 consts_size() + 1023 insts_size() + 1024 stub_size() + 1025 scopes_data_size() + 1026 scopes_pcs_size() + 1027 handler_table_size() + 1028 nul_chk_table_size(); 1029 } 1030 1031 const char* nmethod::compile_kind() const { 1032 if (is_osr_method()) return "osr"; 1033 if (method() != nullptr && is_native_method()) { 1034 if (method()->is_continuation_native_intrinsic()) { 1035 return "cnt"; 1036 } 1037 return "c2n"; 1038 } 1039 return nullptr; 1040 } 1041 1042 const char* nmethod::compiler_name() const { 1043 return compilertype2name(_compiler_type); 1044 } 1045 1046 #ifdef ASSERT 1047 class CheckForOopsClosure : public OopClosure { 1048 bool _found_oop = false; 1049 public: 1050 virtual void do_oop(oop* o) { _found_oop = true; } 1051 virtual void do_oop(narrowOop* o) { _found_oop = true; } 1052 bool found_oop() { return _found_oop; } 1053 }; 1054 class CheckForMetadataClosure : public MetadataClosure { 1055 bool _found_metadata = false; 1056 Metadata* _ignore = nullptr; 1057 public: 1058 CheckForMetadataClosure(Metadata* ignore) : _ignore(ignore) {} 1059 virtual void do_metadata(Metadata* md) { if (md != _ignore) _found_metadata = true; } 1060 bool found_metadata() { return _found_metadata; } 1061 }; 1062 1063 static void assert_no_oops_or_metadata(nmethod* nm) { 1064 if (nm == nullptr) return; 1065 assert(nm->oop_maps() == nullptr, "expectation"); 1066 1067 CheckForOopsClosure cfo; 1068 nm->oops_do(&cfo); 1069 assert(!cfo.found_oop(), "no oops allowed"); 1070 1071 // We allow an exception for the own Method, but require its class to be permanent. 1072 Method* own_method = nm->method(); 1073 CheckForMetadataClosure cfm(/* ignore reference to own Method */ own_method); 1074 nm->metadata_do(&cfm); 1075 assert(!cfm.found_metadata(), "no metadata allowed"); 1076 1077 assert(own_method->method_holder()->class_loader_data()->is_permanent_class_loader_data(), 1078 "Method's class needs to be permanent"); 1079 } 1080 #endif 1081 1082 static int required_mutable_data_size(CodeBuffer* code_buffer, 1083 int jvmci_data_size = 0) { 1084 return align_up(code_buffer->total_relocation_size(), oopSize) + 1085 align_up(code_buffer->total_metadata_size(), oopSize) + 1086 align_up(jvmci_data_size, oopSize); 1087 } 1088 1089 nmethod* nmethod::new_native_nmethod(const methodHandle& method, 1090 int compile_id, 1091 CodeBuffer *code_buffer, 1092 int vep_offset, 1093 int frame_complete, 1094 int frame_size, 1095 ByteSize basic_lock_owner_sp_offset, 1096 ByteSize basic_lock_sp_offset, 1097 OopMapSet* oop_maps, 1098 int exception_handler) { 1099 code_buffer->finalize_oop_references(method); 1100 // create nmethod 1101 nmethod* nm = nullptr; 1102 int native_nmethod_size = CodeBlob::allocation_size(code_buffer, sizeof(nmethod)); 1103 { 1104 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1105 1106 CodeOffsets offsets; 1107 offsets.set_value(CodeOffsets::Verified_Entry, vep_offset); 1108 offsets.set_value(CodeOffsets::Frame_Complete, frame_complete); 1109 if (exception_handler != -1) { 1110 offsets.set_value(CodeOffsets::Exceptions, exception_handler); 1111 } 1112 1113 int mutable_data_size = required_mutable_data_size(code_buffer); 1114 1115 // MH intrinsics are dispatch stubs which are compatible with NonNMethod space. 1116 // IsUnloadingBehaviour::is_unloading needs to handle them separately. 1117 bool allow_NonNMethod_space = method->can_be_allocated_in_NonNMethod_space(); 1118 nm = new (native_nmethod_size, allow_NonNMethod_space) 1119 nmethod(method(), compiler_none, native_nmethod_size, 1120 compile_id, &offsets, 1121 code_buffer, frame_size, 1122 basic_lock_owner_sp_offset, 1123 basic_lock_sp_offset, 1124 oop_maps, mutable_data_size); 1125 DEBUG_ONLY( if (allow_NonNMethod_space) assert_no_oops_or_metadata(nm); ) 1126 NOT_PRODUCT(if (nm != nullptr) native_nmethod_stats.note_native_nmethod(nm)); 1127 } 1128 1129 if (nm != nullptr) { 1130 // verify nmethod 1131 DEBUG_ONLY(nm->verify();) // might block 1132 1133 nm->log_new_nmethod(); 1134 } 1135 return nm; 1136 } 1137 1138 void nmethod::record_nmethod_dependency() { 1139 // To make dependency checking during class loading fast, record 1140 // the nmethod dependencies in the classes it is dependent on. 1141 // This allows the dependency checking code to simply walk the 1142 // class hierarchy above the loaded class, checking only nmethods 1143 // which are dependent on those classes. The slow way is to 1144 // check every nmethod for dependencies which makes it linear in 1145 // the number of methods compiled. For applications with a lot 1146 // classes the slow way is too slow. 1147 for (Dependencies::DepStream deps(this); deps.next(); ) { 1148 if (deps.type() == Dependencies::call_site_target_value) { 1149 // CallSite dependencies are managed on per-CallSite instance basis. 1150 oop call_site = deps.argument_oop(0); 1151 MethodHandles::add_dependent_nmethod(call_site, this); 1152 } else { 1153 InstanceKlass* ik = deps.context_type(); 1154 if (ik == nullptr) { 1155 continue; // ignore things like evol_method 1156 } 1157 // record this nmethod as dependent on this klass 1158 ik->add_dependent_nmethod(this); 1159 } 1160 } 1161 } 1162 1163 nmethod* nmethod::new_nmethod(const methodHandle& method, 1164 int compile_id, 1165 int entry_bci, 1166 CodeOffsets* offsets, 1167 int orig_pc_offset, 1168 DebugInformationRecorder* debug_info, 1169 Dependencies* dependencies, 1170 CodeBuffer* code_buffer, int frame_size, 1171 OopMapSet* oop_maps, 1172 ExceptionHandlerTable* handler_table, 1173 ImplicitExceptionTable* nul_chk_table, 1174 AbstractCompiler* compiler, 1175 CompLevel comp_level 1176 , AOTCodeEntry* aot_code_entry 1177 #if INCLUDE_JVMCI 1178 , char* speculations, 1179 int speculations_len, 1180 JVMCINMethodData* jvmci_data 1181 #endif 1182 ) 1183 { 1184 assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR"); 1185 code_buffer->finalize_oop_references(method); 1186 // create nmethod 1187 nmethod* nm = nullptr; 1188 int nmethod_size = CodeBlob::allocation_size(code_buffer, sizeof(nmethod)); 1189 1190 int immutable_data_size = 1191 adjust_pcs_size(debug_info->pcs_size()) 1192 + align_up((int)dependencies->size_in_bytes(), oopSize) 1193 + align_up(handler_table->size_in_bytes() , oopSize) 1194 + align_up(nul_chk_table->size_in_bytes() , oopSize) 1195 #if INCLUDE_JVMCI 1196 + align_up(speculations_len , oopSize) 1197 #endif 1198 + align_up(debug_info->data_size() , oopSize); 1199 1200 // First, allocate space for immutable data in C heap. 1201 address immutable_data = nullptr; 1202 if (immutable_data_size > 0) { 1203 immutable_data = (address)os::malloc(immutable_data_size, mtCode); 1204 if (immutable_data == nullptr) { 1205 vm_exit_out_of_memory(immutable_data_size, OOM_MALLOC_ERROR, "nmethod: no space for immutable data"); 1206 return nullptr; 1207 } 1208 } 1209 1210 int mutable_data_size = required_mutable_data_size(code_buffer 1211 JVMCI_ONLY(COMMA (compiler->is_jvmci() ? jvmci_data->size() : 0))); 1212 1213 { 1214 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1215 1216 nm = new (nmethod_size, comp_level) 1217 nmethod(method(), compiler->type(), nmethod_size, immutable_data_size, mutable_data_size, 1218 compile_id, entry_bci, immutable_data, offsets, orig_pc_offset, 1219 debug_info, dependencies, code_buffer, frame_size, oop_maps, 1220 handler_table, nul_chk_table, compiler, comp_level, aot_code_entry 1221 #if INCLUDE_JVMCI 1222 , speculations, 1223 speculations_len, 1224 jvmci_data 1225 #endif 1226 ); 1227 1228 if (nm != nullptr) { 1229 nm->record_nmethod_dependency(); 1230 NOT_PRODUCT(note_java_nmethod(nm)); 1231 } 1232 } 1233 // Do verification and logging outside CodeCache_lock. 1234 if (nm != nullptr) { 1235 1236 #ifdef ASSERT 1237 LogTarget(Debug, aot, codecache, nmethod) log; 1238 if (log.is_enabled()) { 1239 LogStream out(log); 1240 out.print_cr("== new_nmethod 2"); 1241 FlagSetting fs(PrintRelocations, true); 1242 nm->print_on_impl(&out); 1243 nm->decode(&out); 1244 } 1245 #endif 1246 1247 // Safepoints in nmethod::verify aren't allowed because nm hasn't been installed yet. 1248 DEBUG_ONLY(nm->verify();) 1249 nm->log_new_nmethod(); 1250 } 1251 return nm; 1252 } 1253 1254 nmethod* nmethod::restore(address code_cache_buffer, 1255 const methodHandle& method, 1256 int compile_id, 1257 address reloc_data, 1258 GrowableArray<Handle>& oop_list, 1259 GrowableArray<Metadata*>& metadata_list, 1260 ImmutableOopMapSet* oop_maps, 1261 address immutable_data, 1262 GrowableArray<Handle>& reloc_imm_oop_list, 1263 GrowableArray<Metadata*>& reloc_imm_metadata_list, 1264 AOTCodeReader* aot_code_reader) 1265 { 1266 CodeBlob::restore(code_cache_buffer, "nmethod", reloc_data, oop_maps); 1267 nmethod* nm = (nmethod*)code_cache_buffer; 1268 nm->set_method(method()); 1269 nm->_compile_id = compile_id; 1270 nm->set_immutable_data(immutable_data); 1271 nm->copy_values(&oop_list); 1272 nm->copy_values(&metadata_list); 1273 1274 aot_code_reader->fix_relocations(nm, &reloc_imm_oop_list, &reloc_imm_metadata_list); 1275 1276 #ifndef PRODUCT 1277 nm->asm_remarks().init(); 1278 aot_code_reader->read_asm_remarks(nm->asm_remarks(), /* use_string_table */ false); 1279 nm->dbg_strings().init(); 1280 aot_code_reader->read_dbg_strings(nm->dbg_strings(), /* use_string_table */ false); 1281 #endif 1282 1283 // Flush the code block 1284 ICache::invalidate_range(nm->code_begin(), nm->code_size()); 1285 1286 // Create cache after PcDesc data is copied - it will be used to initialize cache 1287 nm->_pc_desc_container = new PcDescContainer(nm->scopes_pcs_begin()); 1288 1289 nm->set_aot_code_entry(aot_code_reader->aot_code_entry()); 1290 1291 nm->post_init(); 1292 return nm; 1293 } 1294 1295 nmethod* nmethod::new_nmethod(nmethod* archived_nm, 1296 const methodHandle& method, 1297 AbstractCompiler* compiler, 1298 int compile_id, 1299 address reloc_data, 1300 GrowableArray<Handle>& oop_list, 1301 GrowableArray<Metadata*>& metadata_list, 1302 ImmutableOopMapSet* oop_maps, 1303 address immutable_data, 1304 GrowableArray<Handle>& reloc_imm_oop_list, 1305 GrowableArray<Metadata*>& reloc_imm_metadata_list, 1306 AOTCodeReader* aot_code_reader) 1307 { 1308 nmethod* nm = nullptr; 1309 int nmethod_size = archived_nm->size(); 1310 // create nmethod 1311 { 1312 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1313 address code_cache_buffer = (address)CodeCache::allocate(nmethod_size, CodeCache::get_code_blob_type(archived_nm->comp_level())); 1314 if (code_cache_buffer != nullptr) { 1315 nm = archived_nm->restore(code_cache_buffer, 1316 method, 1317 compile_id, 1318 reloc_data, 1319 oop_list, 1320 metadata_list, 1321 oop_maps, 1322 immutable_data, 1323 reloc_imm_oop_list, 1324 reloc_imm_metadata_list, 1325 aot_code_reader); 1326 nm->record_nmethod_dependency(); 1327 NOT_PRODUCT(note_java_nmethod(nm)); 1328 } 1329 } 1330 // Do verification and logging outside CodeCache_lock. 1331 if (nm != nullptr) { 1332 #ifdef ASSERT 1333 LogTarget(Debug, aot, codecache, nmethod) log; 1334 if (log.is_enabled()) { 1335 LogStream out(log); 1336 out.print_cr("== new_nmethod 2"); 1337 FlagSetting fs(PrintRelocations, true); 1338 nm->print_on_impl(&out); 1339 nm->decode(&out); 1340 } 1341 #endif 1342 // Safepoints in nmethod::verify aren't allowed because nm hasn't been installed yet. 1343 DEBUG_ONLY(nm->verify();) 1344 nm->log_new_nmethod(); 1345 } 1346 return nm; 1347 } 1348 1349 // Fill in default values for various fields 1350 void nmethod::init_defaults(CodeBuffer *code_buffer, CodeOffsets* offsets) { 1351 // avoid uninitialized fields, even for short time periods 1352 _exception_cache = nullptr; 1353 _gc_data = nullptr; 1354 _oops_do_mark_link = nullptr; 1355 _compiled_ic_data = nullptr; 1356 1357 _is_unloading_state = 0; 1358 _state = not_installed; 1359 1360 _has_unsafe_access = 0; 1361 _has_method_handle_invokes = 0; 1362 _has_wide_vectors = 0; 1363 _has_monitors = 0; 1364 _has_scoped_access = 0; 1365 _has_flushed_dependencies = 0; 1366 _is_unlinked = 0; 1367 _load_reported = 0; // jvmti state 1368 _preloaded = 0; 1369 _has_clinit_barriers = 0; 1370 1371 _used = false; 1372 _deoptimization_status = not_marked; 1373 1374 // SECT_CONSTS is first in code buffer so the offset should be 0. 1375 int consts_offset = code_buffer->total_offset_of(code_buffer->consts()); 1376 assert(consts_offset == 0, "const_offset: %d", consts_offset); 1377 1378 _stub_offset = content_offset() + code_buffer->total_offset_of(code_buffer->stubs()); 1379 1380 CHECKED_CAST(_entry_offset, uint16_t, (offsets->value(CodeOffsets::Entry))); 1381 CHECKED_CAST(_verified_entry_offset, uint16_t, (offsets->value(CodeOffsets::Verified_Entry))); 1382 1383 _skipped_instructions_size = code_buffer->total_skipped_instructions_size(); 1384 } 1385 1386 // Post initialization 1387 void nmethod::post_init() { 1388 clear_unloading_state(); 1389 1390 finalize_relocations(); 1391 1392 Universe::heap()->register_nmethod(this); 1393 DEBUG_ONLY(Universe::heap()->verify_nmethod(this)); 1394 1395 CodeCache::commit(this); 1396 } 1397 1398 // For native wrappers 1399 nmethod::nmethod( 1400 Method* method, 1401 CompilerType type, 1402 int nmethod_size, 1403 int compile_id, 1404 CodeOffsets* offsets, 1405 CodeBuffer* code_buffer, 1406 int frame_size, 1407 ByteSize basic_lock_owner_sp_offset, 1408 ByteSize basic_lock_sp_offset, 1409 OopMapSet* oop_maps, 1410 int mutable_data_size) 1411 : CodeBlob("native nmethod", CodeBlobKind::Nmethod, code_buffer, nmethod_size, sizeof(nmethod), 1412 offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps, false, mutable_data_size), 1413 _deoptimization_generation(0), 1414 _gc_epoch(CodeCache::gc_epoch()), 1415 _method(method), 1416 _native_receiver_sp_offset(basic_lock_owner_sp_offset), 1417 _native_basic_lock_sp_offset(basic_lock_sp_offset) 1418 { 1419 { 1420 DEBUG_ONLY(NoSafepointVerifier nsv;) 1421 assert_locked_or_safepoint(CodeCache_lock); 1422 1423 init_defaults(code_buffer, offsets); 1424 1425 _osr_entry_point = nullptr; 1426 _pc_desc_container = nullptr; 1427 _entry_bci = InvocationEntryBci; 1428 _compile_id = compile_id; 1429 _comp_level = CompLevel_none; 1430 _compiler_type = type; 1431 _orig_pc_offset = 0; 1432 _num_stack_arg_slots = 0; 1433 1434 if (offsets->value(CodeOffsets::Exceptions) != -1) { 1435 // Continuation enter intrinsic 1436 _exception_offset = code_offset() + offsets->value(CodeOffsets::Exceptions); 1437 } else { 1438 _exception_offset = 0; 1439 } 1440 // Native wrappers do not have deopt handlers. Make the values 1441 // something that will never match a pc like the nmethod vtable entry 1442 _deopt_handler_offset = 0; 1443 _deopt_mh_handler_offset = 0; 1444 _aot_code_entry = nullptr; 1445 _method_profiling_count = 0; 1446 _unwind_handler_offset = 0; 1447 1448 CHECKED_CAST(_oops_size, uint16_t, align_up(code_buffer->total_oop_size(), oopSize)); 1449 uint16_t metadata_size; 1450 CHECKED_CAST(metadata_size, uint16_t, align_up(code_buffer->total_metadata_size(), wordSize)); 1451 JVMCI_ONLY( _metadata_size = metadata_size; ) 1452 assert(_mutable_data_size == _relocation_size + metadata_size, 1453 "wrong mutable data size: %d != %d + %d", 1454 _mutable_data_size, _relocation_size, metadata_size); 1455 1456 // native wrapper does not have read-only data but we need unique not null address 1457 _immutable_data = blob_end(); 1458 _immutable_data_size = 0; 1459 _nul_chk_table_offset = 0; 1460 _handler_table_offset = 0; 1461 _scopes_pcs_offset = 0; 1462 _scopes_data_offset = 0; 1463 #if INCLUDE_JVMCI 1464 _speculations_offset = 0; 1465 #endif 1466 1467 code_buffer->copy_code_and_locs_to(this); 1468 code_buffer->copy_values_to(this); 1469 1470 post_init(); 1471 } 1472 1473 if (PrintNativeNMethods || PrintDebugInfo || PrintRelocations || PrintDependencies) { 1474 ttyLocker ttyl; // keep the following output all in one block 1475 // This output goes directly to the tty, not the compiler log. 1476 // To enable tools to match it up with the compilation activity, 1477 // be sure to tag this tty output with the compile ID. 1478 if (xtty != nullptr) { 1479 xtty->begin_head("print_native_nmethod"); 1480 xtty->method(_method); 1481 xtty->stamp(); 1482 xtty->end_head(" address='" INTPTR_FORMAT "'", (intptr_t) this); 1483 } 1484 // Print the header part, then print the requested information. 1485 // This is both handled in decode2(), called via print_code() -> decode() 1486 if (PrintNativeNMethods) { 1487 tty->print_cr("-------------------------- Assembly (native nmethod) ---------------------------"); 1488 print_code(); 1489 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1490 #if defined(SUPPORT_DATA_STRUCTS) 1491 if (AbstractDisassembler::show_structs()) { 1492 if (oop_maps != nullptr) { 1493 tty->print("oop maps:"); // oop_maps->print_on(tty) outputs a cr() at the beginning 1494 oop_maps->print_on(tty); 1495 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1496 } 1497 } 1498 #endif 1499 } else { 1500 print(); // print the header part only. 1501 } 1502 #if defined(SUPPORT_DATA_STRUCTS) 1503 if (AbstractDisassembler::show_structs()) { 1504 if (PrintRelocations) { 1505 print_relocations_on(tty); 1506 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1507 } 1508 } 1509 #endif 1510 if (xtty != nullptr) { 1511 xtty->tail("print_native_nmethod"); 1512 } 1513 } 1514 } 1515 1516 void* nmethod::operator new(size_t size, int nmethod_size, int comp_level) throw () { 1517 return CodeCache::allocate(nmethod_size, CodeCache::get_code_blob_type(comp_level)); 1518 } 1519 1520 void* nmethod::operator new(size_t size, int nmethod_size, bool allow_NonNMethod_space) throw () { 1521 // Try MethodNonProfiled and MethodProfiled. 1522 void* return_value = CodeCache::allocate(nmethod_size, CodeBlobType::MethodNonProfiled); 1523 if (return_value != nullptr || !allow_NonNMethod_space) return return_value; 1524 // Try NonNMethod or give up. 1525 return CodeCache::allocate(nmethod_size, CodeBlobType::NonNMethod); 1526 } 1527 1528 // For normal JIT compiled code 1529 nmethod::nmethod( 1530 Method* method, 1531 CompilerType type, 1532 int nmethod_size, 1533 int immutable_data_size, 1534 int mutable_data_size, 1535 int compile_id, 1536 int entry_bci, 1537 address immutable_data, 1538 CodeOffsets* offsets, 1539 int orig_pc_offset, 1540 DebugInformationRecorder* debug_info, 1541 Dependencies* dependencies, 1542 CodeBuffer *code_buffer, 1543 int frame_size, 1544 OopMapSet* oop_maps, 1545 ExceptionHandlerTable* handler_table, 1546 ImplicitExceptionTable* nul_chk_table, 1547 AbstractCompiler* compiler, 1548 CompLevel comp_level 1549 , AOTCodeEntry* aot_code_entry 1550 #if INCLUDE_JVMCI 1551 , char* speculations, 1552 int speculations_len, 1553 JVMCINMethodData* jvmci_data 1554 #endif 1555 ) 1556 : CodeBlob("nmethod", CodeBlobKind::Nmethod, code_buffer, nmethod_size, sizeof(nmethod), 1557 offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps, false, mutable_data_size), 1558 _deoptimization_generation(0), 1559 _gc_epoch(CodeCache::gc_epoch()), 1560 _method(method), 1561 _osr_link(nullptr) 1562 { 1563 assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR"); 1564 { 1565 DEBUG_ONLY(NoSafepointVerifier nsv;) 1566 assert_locked_or_safepoint(CodeCache_lock); 1567 1568 init_defaults(code_buffer, offsets); 1569 _aot_code_entry = aot_code_entry; 1570 _method_profiling_count = 0; 1571 1572 _osr_entry_point = code_begin() + offsets->value(CodeOffsets::OSR_Entry); 1573 _entry_bci = entry_bci; 1574 _compile_id = compile_id; 1575 _comp_level = comp_level; 1576 _compiler_type = type; 1577 _orig_pc_offset = orig_pc_offset; 1578 1579 _num_stack_arg_slots = entry_bci != InvocationEntryBci ? 0 : _method->constMethod()->num_stack_arg_slots(); 1580 1581 set_ctable_begin(header_begin() + content_offset()); 1582 1583 #if INCLUDE_JVMCI 1584 if (compiler->is_jvmci()) { 1585 // JVMCI might not produce any stub sections 1586 if (offsets->value(CodeOffsets::Exceptions) != -1) { 1587 _exception_offset = code_offset() + offsets->value(CodeOffsets::Exceptions); 1588 } else { 1589 _exception_offset = -1; 1590 } 1591 if (offsets->value(CodeOffsets::Deopt) != -1) { 1592 _deopt_handler_offset = code_offset() + offsets->value(CodeOffsets::Deopt); 1593 } else { 1594 _deopt_handler_offset = -1; 1595 } 1596 if (offsets->value(CodeOffsets::DeoptMH) != -1) { 1597 _deopt_mh_handler_offset = code_offset() + offsets->value(CodeOffsets::DeoptMH); 1598 } else { 1599 _deopt_mh_handler_offset = -1; 1600 } 1601 } else 1602 #endif 1603 { 1604 // Exception handler and deopt handler are in the stub section 1605 assert(offsets->value(CodeOffsets::Exceptions) != -1, "must be set"); 1606 assert(offsets->value(CodeOffsets::Deopt ) != -1, "must be set"); 1607 1608 _exception_offset = _stub_offset + offsets->value(CodeOffsets::Exceptions); 1609 _deopt_handler_offset = _stub_offset + offsets->value(CodeOffsets::Deopt); 1610 if (offsets->value(CodeOffsets::DeoptMH) != -1) { 1611 _deopt_mh_handler_offset = _stub_offset + offsets->value(CodeOffsets::DeoptMH); 1612 } else { 1613 _deopt_mh_handler_offset = -1; 1614 } 1615 } 1616 if (offsets->value(CodeOffsets::UnwindHandler) != -1) { 1617 // C1 generates UnwindHandler at the end of instructions section. 1618 // Calculate positive offset as distance between the start of stubs section 1619 // (which is also the end of instructions section) and the start of the handler. 1620 int unwind_handler_offset = code_offset() + offsets->value(CodeOffsets::UnwindHandler); 1621 CHECKED_CAST(_unwind_handler_offset, int16_t, (_stub_offset - unwind_handler_offset)); 1622 } else { 1623 _unwind_handler_offset = -1; 1624 } 1625 1626 CHECKED_CAST(_oops_size, uint16_t, align_up(code_buffer->total_oop_size(), oopSize)); 1627 uint16_t metadata_size; 1628 CHECKED_CAST(metadata_size, uint16_t, align_up(code_buffer->total_metadata_size(), wordSize)); 1629 JVMCI_ONLY( _metadata_size = metadata_size; ) 1630 int jvmci_data_size = 0 JVMCI_ONLY( + align_up(compiler->is_jvmci() ? jvmci_data->size() : 0, oopSize)); 1631 assert(_mutable_data_size == _relocation_size + metadata_size + jvmci_data_size, 1632 "wrong mutable data size: %d != %d + %d + %d", 1633 _mutable_data_size, _relocation_size, metadata_size, jvmci_data_size); 1634 assert(nmethod_size == data_end() - header_begin(), "wrong nmethod size: %d != %d", 1635 nmethod_size, (int)(code_end() - header_begin())); 1636 1637 _immutable_data_size = immutable_data_size; 1638 if (immutable_data_size > 0) { 1639 assert(immutable_data != nullptr, "required"); 1640 _immutable_data = immutable_data; 1641 } else { 1642 // We need unique not null address 1643 _immutable_data = blob_end(); 1644 } 1645 CHECKED_CAST(_nul_chk_table_offset, uint16_t, (align_up((int)dependencies->size_in_bytes(), oopSize))); 1646 CHECKED_CAST(_handler_table_offset, uint16_t, (_nul_chk_table_offset + align_up(nul_chk_table->size_in_bytes(), oopSize))); 1647 _scopes_pcs_offset = _handler_table_offset + align_up(handler_table->size_in_bytes(), oopSize); 1648 _scopes_data_offset = _scopes_pcs_offset + adjust_pcs_size(debug_info->pcs_size()); 1649 1650 #if INCLUDE_JVMCI 1651 _speculations_offset = _scopes_data_offset + align_up(debug_info->data_size(), oopSize); 1652 DEBUG_ONLY( int immutable_data_end_offset = _speculations_offset + align_up(speculations_len, oopSize); ) 1653 #else 1654 DEBUG_ONLY( int immutable_data_end_offset = _scopes_data_offset + align_up(debug_info->data_size(), oopSize); ) 1655 #endif 1656 assert(immutable_data_end_offset <= immutable_data_size, "wrong read-only data size: %d > %d", 1657 immutable_data_end_offset, immutable_data_size); 1658 1659 // Copy code and relocation info 1660 code_buffer->copy_code_and_locs_to(this); 1661 // Copy oops and metadata 1662 code_buffer->copy_values_to(this); 1663 dependencies->copy_to(this); 1664 // Copy PcDesc and ScopeDesc data 1665 debug_info->copy_to(this); 1666 1667 // Create cache after PcDesc data is copied - it will be used to initialize cache 1668 _pc_desc_container = new PcDescContainer(scopes_pcs_begin()); 1669 1670 #if INCLUDE_JVMCI 1671 if (compiler->is_jvmci()) { 1672 // Initialize the JVMCINMethodData object inlined into nm 1673 jvmci_nmethod_data()->copy(jvmci_data); 1674 } 1675 #endif 1676 1677 // Copy contents of ExceptionHandlerTable to nmethod 1678 handler_table->copy_to(this); 1679 nul_chk_table->copy_to(this); 1680 1681 #if INCLUDE_JVMCI 1682 // Copy speculations to nmethod 1683 if (speculations_size() != 0) { 1684 memcpy(speculations_begin(), speculations, speculations_len); 1685 } 1686 #endif 1687 1688 post_init(); 1689 1690 // we use the information of entry points to find out if a method is 1691 // static or non static 1692 assert(compiler->is_c2() || compiler->is_jvmci() || 1693 _method->is_static() == (entry_point() == verified_entry_point()), 1694 " entry points must be same for static methods and vice versa"); 1695 } 1696 } 1697 1698 // Print a short set of xml attributes to identify this nmethod. The 1699 // output should be embedded in some other element. 1700 void nmethod::log_identity(xmlStream* log) const { 1701 assert(log->inside_attrs_or_error(), "printing attributes"); 1702 log->print(" code_compile_id='%d'", compile_id()); 1703 const char* nm_kind = compile_kind(); 1704 if (nm_kind != nullptr) log->print(" code_compile_kind='%s'", nm_kind); 1705 log->print(" code_compiler='%s'", compiler_name()); 1706 if (TieredCompilation) { 1707 log->print(" code_compile_level='%d'", comp_level()); 1708 } 1709 #if INCLUDE_JVMCI 1710 if (jvmci_nmethod_data() != nullptr) { 1711 const char* jvmci_name = jvmci_nmethod_data()->name(); 1712 if (jvmci_name != nullptr) { 1713 log->print(" jvmci_mirror_name='"); 1714 log->text("%s", jvmci_name); 1715 log->print("'"); 1716 } 1717 } 1718 #endif 1719 } 1720 1721 1722 #define LOG_OFFSET(log, name) \ 1723 if (p2i(name##_end()) - p2i(name##_begin())) \ 1724 log->print(" " XSTR(name) "_offset='%zd'" , \ 1725 p2i(name##_begin()) - p2i(this)) 1726 1727 1728 void nmethod::log_new_nmethod() const { 1729 if (LogCompilation && xtty != nullptr) { 1730 ttyLocker ttyl; 1731 xtty->begin_elem("nmethod"); 1732 log_identity(xtty); 1733 xtty->print(" entry='" INTPTR_FORMAT "' size='%d'", p2i(code_begin()), size()); 1734 xtty->print(" address='" INTPTR_FORMAT "'", p2i(this)); 1735 1736 LOG_OFFSET(xtty, relocation); 1737 LOG_OFFSET(xtty, consts); 1738 LOG_OFFSET(xtty, insts); 1739 LOG_OFFSET(xtty, stub); 1740 LOG_OFFSET(xtty, scopes_data); 1741 LOG_OFFSET(xtty, scopes_pcs); 1742 LOG_OFFSET(xtty, dependencies); 1743 LOG_OFFSET(xtty, handler_table); 1744 LOG_OFFSET(xtty, nul_chk_table); 1745 LOG_OFFSET(xtty, oops); 1746 LOG_OFFSET(xtty, metadata); 1747 1748 xtty->method(method()); 1749 xtty->stamp(); 1750 xtty->end_elem(); 1751 } 1752 } 1753 1754 #undef LOG_OFFSET 1755 1756 1757 // Print out more verbose output usually for a newly created nmethod. 1758 void nmethod::print_on_with_msg(outputStream* st, const char* msg) const { 1759 if (st != nullptr) { 1760 ttyLocker ttyl; 1761 if (WizardMode) { 1762 CompileTask::print(st, this, msg, /*short_form:*/ true); 1763 st->print_cr(" (" INTPTR_FORMAT ")", p2i(this)); 1764 } else { 1765 CompileTask::print(st, this, msg, /*short_form:*/ false); 1766 } 1767 } 1768 } 1769 1770 void nmethod::maybe_print_nmethod(const DirectiveSet* directive) { 1771 bool printnmethods = directive->PrintAssemblyOption || directive->PrintNMethodsOption; 1772 if (printnmethods || PrintDebugInfo || PrintRelocations || PrintDependencies || PrintExceptionHandlers) { 1773 print_nmethod(printnmethods); 1774 } 1775 } 1776 1777 void nmethod::print_nmethod(bool printmethod) { 1778 // Enter a critical section to prevent a race with deopts that patch code and updates the relocation info. 1779 // Unfortunately, we have to lock the NMethodState_lock before the tty lock due to the deadlock rules and 1780 // cannot lock in a more finely grained manner. 1781 ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag); 1782 ttyLocker ttyl; // keep the following output all in one block 1783 if (xtty != nullptr) { 1784 xtty->begin_head("print_nmethod"); 1785 log_identity(xtty); 1786 xtty->stamp(); 1787 xtty->end_head(); 1788 } 1789 // Print the header part, then print the requested information. 1790 // This is both handled in decode2(). 1791 if (printmethod) { 1792 ResourceMark m; 1793 if (is_compiled_by_c1()) { 1794 tty->cr(); 1795 tty->print_cr("============================= C1-compiled nmethod =============================="); 1796 } 1797 if (is_compiled_by_jvmci()) { 1798 tty->cr(); 1799 tty->print_cr("=========================== JVMCI-compiled nmethod ============================="); 1800 } 1801 tty->print_cr("----------------------------------- Assembly -----------------------------------"); 1802 decode2(tty); 1803 #if defined(SUPPORT_DATA_STRUCTS) 1804 if (AbstractDisassembler::show_structs()) { 1805 // Print the oops from the underlying CodeBlob as well. 1806 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1807 print_oops(tty); 1808 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1809 print_metadata(tty); 1810 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1811 print_pcs_on(tty); 1812 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1813 if (oop_maps() != nullptr) { 1814 tty->print("oop maps:"); // oop_maps()->print_on(tty) outputs a cr() at the beginning 1815 oop_maps()->print_on(tty); 1816 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1817 } 1818 } 1819 #endif 1820 } else { 1821 print(); // print the header part only. 1822 } 1823 1824 #if defined(SUPPORT_DATA_STRUCTS) 1825 if (AbstractDisassembler::show_structs()) { 1826 methodHandle mh(Thread::current(), _method); 1827 if (printmethod || PrintDebugInfo || CompilerOracle::has_option(mh, CompileCommandEnum::PrintDebugInfo)) { 1828 print_scopes(); 1829 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1830 } 1831 if (printmethod || PrintRelocations || CompilerOracle::has_option(mh, CompileCommandEnum::PrintRelocations)) { 1832 print_relocations_on(tty); 1833 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1834 } 1835 if (printmethod || PrintDependencies || CompilerOracle::has_option(mh, CompileCommandEnum::PrintDependencies)) { 1836 print_dependencies_on(tty); 1837 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1838 } 1839 if (printmethod || PrintExceptionHandlers) { 1840 print_handler_table(); 1841 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1842 print_nul_chk_table(); 1843 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1844 } 1845 1846 if (printmethod) { 1847 print_recorded_oops(); 1848 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1849 print_recorded_metadata(); 1850 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1851 } 1852 } 1853 #endif 1854 1855 if (xtty != nullptr) { 1856 xtty->tail("print_nmethod"); 1857 } 1858 } 1859 1860 1861 // Promote one word from an assembly-time handle to a live embedded oop. 1862 inline void nmethod::initialize_immediate_oop(oop* dest, jobject handle) { 1863 if (handle == nullptr || 1864 // As a special case, IC oops are initialized to 1 or -1. 1865 handle == (jobject) Universe::non_oop_word()) { 1866 *(void**)dest = handle; 1867 } else { 1868 *dest = JNIHandles::resolve_non_null(handle); 1869 } 1870 } 1871 1872 void nmethod::copy_values(GrowableArray<Handle>* array) { 1873 int length = array->length(); 1874 assert((address)(oops_begin() + length) <= (address)oops_end(), "oops big enough"); 1875 oop* dest = oops_begin(); 1876 for (int index = 0 ; index < length; index++) { 1877 dest[index] = array->at(index)(); 1878 } 1879 } 1880 1881 // Have to have the same name because it's called by a template 1882 void nmethod::copy_values(GrowableArray<jobject>* array) { 1883 int length = array->length(); 1884 assert((address)(oops_begin() + length) <= (address)oops_end(), "oops big enough"); 1885 oop* dest = oops_begin(); 1886 for (int index = 0 ; index < length; index++) { 1887 initialize_immediate_oop(&dest[index], array->at(index)); 1888 } 1889 1890 // Now we can fix up all the oops in the code. We need to do this 1891 // in the code because the assembler uses jobjects as placeholders. 1892 // The code and relocations have already been initialized by the 1893 // CodeBlob constructor, so it is valid even at this early point to 1894 // iterate over relocations and patch the code. 1895 fix_oop_relocations(nullptr, nullptr, /*initialize_immediates=*/ true); 1896 } 1897 1898 void nmethod::copy_values(GrowableArray<Metadata*>* array) { 1899 int length = array->length(); 1900 assert((address)(metadata_begin() + length) <= (address)metadata_end(), "big enough"); 1901 Metadata** dest = metadata_begin(); 1902 for (int index = 0 ; index < length; index++) { 1903 dest[index] = array->at(index); 1904 } 1905 } 1906 1907 void nmethod::fix_oop_relocations(address begin, address end, bool initialize_immediates) { 1908 // re-patch all oop-bearing instructions, just in case some oops moved 1909 RelocIterator iter(this, begin, end); 1910 while (iter.next()) { 1911 if (iter.type() == relocInfo::oop_type) { 1912 oop_Relocation* reloc = iter.oop_reloc(); 1913 if (initialize_immediates && reloc->oop_is_immediate()) { 1914 oop* dest = reloc->oop_addr(); 1915 jobject obj = *reinterpret_cast<jobject*>(dest); 1916 initialize_immediate_oop(dest, obj); 1917 } 1918 // Refresh the oop-related bits of this instruction. 1919 reloc->fix_oop_relocation(); 1920 } else if (iter.type() == relocInfo::metadata_type) { 1921 metadata_Relocation* reloc = iter.metadata_reloc(); 1922 reloc->fix_metadata_relocation(); 1923 } 1924 } 1925 } 1926 1927 void nmethod::create_reloc_immediates_list(JavaThread* thread, GrowableArray<Handle>& oop_list, GrowableArray<Metadata*>& metadata_list) { 1928 RelocIterator iter(this); 1929 while (iter.next()) { 1930 if (iter.type() == relocInfo::oop_type) { 1931 oop_Relocation* reloc = iter.oop_reloc(); 1932 if (reloc->oop_is_immediate()) { 1933 oop dest = reloc->oop_value(); 1934 Handle h(thread, dest); 1935 oop_list.append(h); 1936 } 1937 } else if (iter.type() == relocInfo::metadata_type) { 1938 metadata_Relocation* reloc = iter.metadata_reloc(); 1939 if (reloc->metadata_is_immediate()) { 1940 Metadata* m = reloc->metadata_value(); 1941 metadata_list.append(m); 1942 } 1943 } 1944 } 1945 } 1946 1947 static void install_post_call_nop_displacement(nmethod* nm, address pc) { 1948 NativePostCallNop* nop = nativePostCallNop_at((address) pc); 1949 intptr_t cbaddr = (intptr_t) nm; 1950 intptr_t offset = ((intptr_t) pc) - cbaddr; 1951 1952 int oopmap_slot = nm->oop_maps()->find_slot_for_offset(int((intptr_t) pc - (intptr_t) nm->code_begin())); 1953 if (oopmap_slot < 0) { // this can happen at asynchronous (non-safepoint) stackwalks 1954 log_debug(codecache)("failed to find oopmap for cb: " INTPTR_FORMAT " offset: %d", cbaddr, (int) offset); 1955 } else if (!nop->patch(oopmap_slot, offset)) { 1956 log_debug(codecache)("failed to encode %d %d", oopmap_slot, (int) offset); 1957 } 1958 } 1959 1960 void nmethod::finalize_relocations() { 1961 NoSafepointVerifier nsv; 1962 1963 GrowableArray<NativeMovConstReg*> virtual_call_data; 1964 1965 // Make sure that post call nops fill in nmethod offsets eagerly so 1966 // we don't have to race with deoptimization 1967 RelocIterator iter(this); 1968 while (iter.next()) { 1969 if (iter.type() == relocInfo::virtual_call_type) { 1970 virtual_call_Relocation* r = iter.virtual_call_reloc(); 1971 NativeMovConstReg* value = nativeMovConstReg_at(r->cached_value()); 1972 virtual_call_data.append(value); 1973 } else if (iter.type() == relocInfo::post_call_nop_type) { 1974 post_call_nop_Relocation* const reloc = iter.post_call_nop_reloc(); 1975 address pc = reloc->addr(); 1976 install_post_call_nop_displacement(this, pc); 1977 } 1978 } 1979 1980 if (virtual_call_data.length() > 0) { 1981 // We allocate a block of CompiledICData per nmethod so the GC can purge this faster. 1982 _compiled_ic_data = new CompiledICData[virtual_call_data.length()]; 1983 CompiledICData* next_data = _compiled_ic_data; 1984 1985 for (NativeMovConstReg* value : virtual_call_data) { 1986 value->set_data((intptr_t)next_data); 1987 next_data++; 1988 } 1989 } 1990 } 1991 1992 void nmethod::make_deoptimized() { 1993 if (!Continuations::enabled()) { 1994 // Don't deopt this again. 1995 set_deoptimized_done(); 1996 return; 1997 } 1998 1999 assert(method() == nullptr || can_be_deoptimized(), ""); 2000 2001 CompiledICLocker ml(this); 2002 assert(CompiledICLocker::is_safe(this), "mt unsafe call"); 2003 2004 // If post call nops have been already patched, we can just bail-out. 2005 if (has_been_deoptimized()) { 2006 return; 2007 } 2008 2009 ResourceMark rm; 2010 RelocIterator iter(this, oops_reloc_begin()); 2011 2012 while (iter.next()) { 2013 2014 switch (iter.type()) { 2015 case relocInfo::virtual_call_type: { 2016 CompiledIC *ic = CompiledIC_at(&iter); 2017 address pc = ic->end_of_call(); 2018 NativePostCallNop* nop = nativePostCallNop_at(pc); 2019 if (nop != nullptr) { 2020 nop->make_deopt(); 2021 } 2022 assert(NativeDeoptInstruction::is_deopt_at(pc), "check"); 2023 break; 2024 } 2025 case relocInfo::static_call_type: 2026 case relocInfo::opt_virtual_call_type: { 2027 CompiledDirectCall *csc = CompiledDirectCall::at(iter.reloc()); 2028 address pc = csc->end_of_call(); 2029 NativePostCallNop* nop = nativePostCallNop_at(pc); 2030 //tty->print_cr(" - static pc %p", pc); 2031 if (nop != nullptr) { 2032 nop->make_deopt(); 2033 } 2034 // We can't assert here, there are some calls to stubs / runtime 2035 // that have reloc data and doesn't have a post call NOP. 2036 //assert(NativeDeoptInstruction::is_deopt_at(pc), "check"); 2037 break; 2038 } 2039 default: 2040 break; 2041 } 2042 } 2043 // Don't deopt this again. 2044 set_deoptimized_done(); 2045 } 2046 2047 void nmethod::verify_clean_inline_caches() { 2048 assert(CompiledICLocker::is_safe(this), "mt unsafe call"); 2049 2050 ResourceMark rm; 2051 RelocIterator iter(this, oops_reloc_begin()); 2052 while(iter.next()) { 2053 switch(iter.type()) { 2054 case relocInfo::virtual_call_type: { 2055 CompiledIC *ic = CompiledIC_at(&iter); 2056 CodeBlob *cb = CodeCache::find_blob(ic->destination()); 2057 assert(cb != nullptr, "destination not in CodeBlob?"); 2058 nmethod* nm = cb->as_nmethod_or_null(); 2059 if (nm != nullptr) { 2060 // Verify that inline caches pointing to bad nmethods are clean 2061 if (!nm->is_in_use() || nm->is_unloading()) { 2062 assert(ic->is_clean(), "IC should be clean"); 2063 } 2064 } 2065 break; 2066 } 2067 case relocInfo::static_call_type: 2068 case relocInfo::opt_virtual_call_type: { 2069 CompiledDirectCall *cdc = CompiledDirectCall::at(iter.reloc()); 2070 CodeBlob *cb = CodeCache::find_blob(cdc->destination()); 2071 assert(cb != nullptr, "destination not in CodeBlob?"); 2072 nmethod* nm = cb->as_nmethod_or_null(); 2073 if (nm != nullptr) { 2074 // Verify that inline caches pointing to bad nmethods are clean 2075 if (!nm->is_in_use() || nm->is_unloading() || nm->method()->code() != nm) { 2076 assert(cdc->is_clean(), "IC should be clean"); 2077 } 2078 } 2079 break; 2080 } 2081 default: 2082 break; 2083 } 2084 } 2085 } 2086 2087 void nmethod::mark_as_maybe_on_stack() { 2088 Atomic::store(&_gc_epoch, CodeCache::gc_epoch()); 2089 } 2090 2091 bool nmethod::is_maybe_on_stack() { 2092 // If the condition below is true, it means that the nmethod was found to 2093 // be alive the previous completed marking cycle. 2094 return Atomic::load(&_gc_epoch) >= CodeCache::previous_completed_gc_marking_cycle(); 2095 } 2096 2097 void nmethod::inc_decompile_count() { 2098 if (!is_compiled_by_c2() && !is_compiled_by_jvmci()) return; 2099 // Could be gated by ProfileTraps, but do not bother... 2100 Method* m = method(); 2101 if (m == nullptr) return; 2102 MethodData* mdo = m->method_data(); 2103 if (mdo == nullptr) return; 2104 // There is a benign race here. See comments in methodData.hpp. 2105 mdo->inc_decompile_count(); 2106 } 2107 2108 void nmethod::inc_method_profiling_count() { 2109 Atomic::inc(&_method_profiling_count); 2110 } 2111 2112 uint64_t nmethod::method_profiling_count() { 2113 return _method_profiling_count; 2114 } 2115 2116 bool nmethod::try_transition(signed char new_state_int) { 2117 signed char new_state = new_state_int; 2118 assert_lock_strong(NMethodState_lock); 2119 signed char old_state = _state; 2120 if (old_state >= new_state) { 2121 // Ensure monotonicity of transitions. 2122 return false; 2123 } 2124 Atomic::store(&_state, new_state); 2125 return true; 2126 } 2127 2128 void nmethod::invalidate_osr_method() { 2129 assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod"); 2130 // Remove from list of active nmethods 2131 if (method() != nullptr) { 2132 method()->method_holder()->remove_osr_nmethod(this); 2133 } 2134 } 2135 2136 void nmethod::log_state_change(const char* reason) const { 2137 assert(reason != nullptr, "Must provide a reason"); 2138 2139 if (LogCompilation) { 2140 if (xtty != nullptr) { 2141 ttyLocker ttyl; // keep the following output all in one block 2142 xtty->begin_elem("make_not_entrant thread='%zu' reason='%s'", 2143 os::current_thread_id(), reason); 2144 log_identity(xtty); 2145 xtty->stamp(); 2146 xtty->end_elem(); 2147 } 2148 } 2149 2150 ResourceMark rm; 2151 stringStream ss(NEW_RESOURCE_ARRAY(char, 256), 256); 2152 ss.print("made not entrant: %s", reason); 2153 2154 CompileTask::print_ul(this, ss.freeze()); 2155 if (PrintCompilation) { 2156 print_on_with_msg(tty, ss.freeze()); 2157 } 2158 } 2159 2160 void nmethod::unlink_from_method() { 2161 if (method() != nullptr) { 2162 method()->unlink_code(this); 2163 } 2164 } 2165 2166 // Invalidate code 2167 bool nmethod::make_not_entrant(const char* reason, bool make_not_entrant) { 2168 assert(reason != nullptr, "Must provide a reason"); 2169 2170 // This can be called while the system is already at a safepoint which is ok 2171 NoSafepointVerifier nsv; 2172 2173 if (is_unloading()) { 2174 // If the nmethod is unloading, then it is already not entrant through 2175 // the nmethod entry barriers. No need to do anything; GC will unload it. 2176 return false; 2177 } 2178 2179 if (Atomic::load(&_state) == not_entrant) { 2180 // Avoid taking the lock if already in required state. 2181 // This is safe from races because the state is an end-state, 2182 // which the nmethod cannot back out of once entered. 2183 // No need for fencing either. 2184 return false; 2185 } 2186 2187 { 2188 // Enter critical section. Does not block for safepoint. 2189 ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag); 2190 2191 if (Atomic::load(&_state) == not_entrant) { 2192 // another thread already performed this transition so nothing 2193 // to do, but return false to indicate this. 2194 return false; 2195 } 2196 2197 if (is_osr_method()) { 2198 // This logic is equivalent to the logic below for patching the 2199 // verified entry point of regular methods. 2200 // this effectively makes the osr nmethod not entrant 2201 invalidate_osr_method(); 2202 } else { 2203 // The caller can be calling the method statically or through an inline 2204 // cache call. 2205 NativeJump::patch_verified_entry(entry_point(), verified_entry_point(), 2206 SharedRuntime::get_handle_wrong_method_stub()); 2207 2208 // Update the relocation info for the patched entry. 2209 // First, get the old relocation info... 2210 RelocIterator iter(this, verified_entry_point(), verified_entry_point() + 8); 2211 if (iter.next() && iter.addr() == verified_entry_point()) { 2212 Relocation* old_reloc = iter.reloc(); 2213 // ...then reset the iterator to update it. 2214 RelocIterator iter(this, verified_entry_point(), verified_entry_point() + 8); 2215 relocInfo::change_reloc_info_for_address(&iter, verified_entry_point(), old_reloc->type(), 2216 relocInfo::relocType::runtime_call_type); 2217 } 2218 } 2219 2220 if (update_recompile_counts()) { 2221 // Mark the method as decompiled. 2222 inc_decompile_count(); 2223 } 2224 2225 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod(); 2226 if (bs_nm == nullptr || !bs_nm->supports_entry_barrier(this)) { 2227 // If nmethod entry barriers are not supported, we won't mark 2228 // nmethods as on-stack when they become on-stack. So we 2229 // degrade to a less accurate flushing strategy, for now. 2230 mark_as_maybe_on_stack(); 2231 } 2232 2233 // Change state 2234 bool success = try_transition(not_entrant); 2235 assert(success, "Transition can't fail"); 2236 2237 // Log the transition once 2238 log_state_change(reason); 2239 2240 // Remove nmethod from method. 2241 unlink_from_method(); 2242 2243 if (make_not_entrant) { 2244 // Keep cached code if it was simply replaced 2245 // otherwise make it not entrant too. 2246 AOTCodeCache::invalidate(_aot_code_entry); 2247 } 2248 2249 CompileBroker::log_not_entrant(this); 2250 } // leave critical region under NMethodState_lock 2251 2252 #if INCLUDE_JVMCI 2253 // Invalidate can't occur while holding the NMethodState_lock 2254 JVMCINMethodData* nmethod_data = jvmci_nmethod_data(); 2255 if (nmethod_data != nullptr) { 2256 nmethod_data->invalidate_nmethod_mirror(this); 2257 } 2258 #endif 2259 2260 #ifdef ASSERT 2261 if (is_osr_method() && method() != nullptr) { 2262 // Make sure osr nmethod is invalidated, i.e. not on the list 2263 bool found = method()->method_holder()->remove_osr_nmethod(this); 2264 assert(!found, "osr nmethod should have been invalidated"); 2265 } 2266 #endif 2267 2268 return true; 2269 } 2270 2271 // For concurrent GCs, there must be a handshake between unlink and flush 2272 void nmethod::unlink() { 2273 if (is_unlinked()) { 2274 // Already unlinked. 2275 return; 2276 } 2277 2278 flush_dependencies(); 2279 2280 // unlink_from_method will take the NMethodState_lock. 2281 // In this case we don't strictly need it when unlinking nmethods from 2282 // the Method, because it is only concurrently unlinked by 2283 // the entry barrier, which acquires the per nmethod lock. 2284 unlink_from_method(); 2285 2286 if (is_osr_method()) { 2287 invalidate_osr_method(); 2288 } 2289 2290 #if INCLUDE_JVMCI 2291 // Clear the link between this nmethod and a HotSpotNmethod mirror 2292 JVMCINMethodData* nmethod_data = jvmci_nmethod_data(); 2293 if (nmethod_data != nullptr) { 2294 nmethod_data->invalidate_nmethod_mirror(this); 2295 } 2296 #endif 2297 2298 // Post before flushing as jmethodID is being used 2299 post_compiled_method_unload(); 2300 2301 // Register for flushing when it is safe. For concurrent class unloading, 2302 // that would be after the unloading handshake, and for STW class unloading 2303 // that would be when getting back to the VM thread. 2304 ClassUnloadingContext::context()->register_unlinked_nmethod(this); 2305 } 2306 2307 void nmethod::purge(bool unregister_nmethod) { 2308 2309 MutexLocker ml(CodeCache_lock, Mutex::_no_safepoint_check_flag); 2310 2311 // completely deallocate this method 2312 Events::log_nmethod_flush(Thread::current(), "flushing %s nmethod " INTPTR_FORMAT, is_osr_method() ? "osr" : "", p2i(this)); 2313 log_debug(codecache)("*flushing %s nmethod %3d/" INTPTR_FORMAT ". Live blobs:" UINT32_FORMAT 2314 "/Free CodeCache:%zuKb", 2315 is_osr_method() ? "osr" : "",_compile_id, p2i(this), CodeCache::blob_count(), 2316 CodeCache::unallocated_capacity(CodeCache::get_code_blob_type(this))/1024); 2317 2318 // We need to deallocate any ExceptionCache data. 2319 // Note that we do not need to grab the nmethod lock for this, it 2320 // better be thread safe if we're disposing of it! 2321 ExceptionCache* ec = exception_cache(); 2322 while(ec != nullptr) { 2323 ExceptionCache* next = ec->next(); 2324 delete ec; 2325 ec = next; 2326 } 2327 if (_pc_desc_container != nullptr) { 2328 delete _pc_desc_container; 2329 } 2330 if (_compiled_ic_data != nullptr) { 2331 delete[] _compiled_ic_data; 2332 } 2333 2334 if (_immutable_data != data_end() && !AOTCodeCache::is_address_in_aot_cache((address)_oop_maps)) { 2335 os::free(_immutable_data); 2336 _immutable_data = blob_end(); // Valid not null address 2337 } 2338 if (unregister_nmethod) { 2339 Universe::heap()->unregister_nmethod(this); 2340 } 2341 CodeCache::unregister_old_nmethod(this); 2342 2343 CodeBlob::purge(); 2344 } 2345 2346 oop nmethod::oop_at(int index) const { 2347 if (index == 0) { 2348 return nullptr; 2349 } 2350 2351 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod(); 2352 return bs_nm->oop_load_no_keepalive(this, index); 2353 } 2354 2355 oop nmethod::oop_at_phantom(int index) const { 2356 if (index == 0) { 2357 return nullptr; 2358 } 2359 2360 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod(); 2361 return bs_nm->oop_load_phantom(this, index); 2362 } 2363 2364 // 2365 // Notify all classes this nmethod is dependent on that it is no 2366 // longer dependent. 2367 2368 void nmethod::flush_dependencies() { 2369 if (!has_flushed_dependencies()) { 2370 set_has_flushed_dependencies(true); 2371 for (Dependencies::DepStream deps(this); deps.next(); ) { 2372 if (deps.type() == Dependencies::call_site_target_value) { 2373 // CallSite dependencies are managed on per-CallSite instance basis. 2374 oop call_site = deps.argument_oop(0); 2375 MethodHandles::clean_dependency_context(call_site); 2376 } else { 2377 InstanceKlass* ik = deps.context_type(); 2378 if (ik == nullptr) { 2379 continue; // ignore things like evol_method 2380 } 2381 // During GC liveness of dependee determines class that needs to be updated. 2382 // The GC may clean dependency contexts concurrently and in parallel. 2383 ik->clean_dependency_context(); 2384 } 2385 } 2386 } 2387 } 2388 2389 void nmethod::post_compiled_method(CompileTask* task) { 2390 task->mark_success(); 2391 task->set_nm_content_size(content_size()); 2392 task->set_nm_insts_size(insts_size()); 2393 task->set_nm_total_size(total_size()); 2394 2395 // task->is_aot() is true only for loaded cached code. 2396 // nmethod::_aot_code_entry is set for loaded and stored cached code 2397 // to invalidate the entry when nmethod is deoptimized. 2398 // There is option to not store in archive cached code. 2399 guarantee((_aot_code_entry != nullptr) || !task->is_aot() || VerifyCachedCode, "sanity"); 2400 2401 // JVMTI -- compiled method notification (must be done outside lock) 2402 post_compiled_method_load_event(); 2403 2404 if (CompilationLog::log() != nullptr) { 2405 CompilationLog::log()->log_nmethod(JavaThread::current(), this); 2406 } 2407 2408 const DirectiveSet* directive = task->directive(); 2409 maybe_print_nmethod(directive); 2410 } 2411 2412 // ------------------------------------------------------------------ 2413 // post_compiled_method_load_event 2414 // new method for install_code() path 2415 // Transfer information from compilation to jvmti 2416 void nmethod::post_compiled_method_load_event(JvmtiThreadState* state) { 2417 // This is a bad time for a safepoint. We don't want 2418 // this nmethod to get unloaded while we're queueing the event. 2419 NoSafepointVerifier nsv; 2420 2421 Method* m = method(); 2422 HOTSPOT_COMPILED_METHOD_LOAD( 2423 (char *) m->klass_name()->bytes(), 2424 m->klass_name()->utf8_length(), 2425 (char *) m->name()->bytes(), 2426 m->name()->utf8_length(), 2427 (char *) m->signature()->bytes(), 2428 m->signature()->utf8_length(), 2429 insts_begin(), insts_size()); 2430 2431 2432 if (JvmtiExport::should_post_compiled_method_load()) { 2433 // Only post unload events if load events are found. 2434 set_load_reported(); 2435 // If a JavaThread hasn't been passed in, let the Service thread 2436 // (which is a real Java thread) post the event 2437 JvmtiDeferredEvent event = JvmtiDeferredEvent::compiled_method_load_event(this); 2438 if (state == nullptr) { 2439 // Execute any barrier code for this nmethod as if it's called, since 2440 // keeping it alive looks like stack walking. 2441 run_nmethod_entry_barrier(); 2442 ServiceThread::enqueue_deferred_event(&event); 2443 } else { 2444 // This enters the nmethod barrier outside in the caller. 2445 state->enqueue_event(&event); 2446 } 2447 } 2448 } 2449 2450 void nmethod::post_compiled_method_unload() { 2451 assert(_method != nullptr, "just checking"); 2452 DTRACE_METHOD_UNLOAD_PROBE(method()); 2453 2454 // If a JVMTI agent has enabled the CompiledMethodUnload event then 2455 // post the event. The Method* will not be valid when this is freed. 2456 2457 // Don't bother posting the unload if the load event wasn't posted. 2458 if (load_reported() && JvmtiExport::should_post_compiled_method_unload()) { 2459 JvmtiDeferredEvent event = 2460 JvmtiDeferredEvent::compiled_method_unload_event( 2461 method()->jmethod_id(), insts_begin()); 2462 ServiceThread::enqueue_deferred_event(&event); 2463 } 2464 } 2465 2466 // Iterate over metadata calling this function. Used by RedefineClasses 2467 void nmethod::metadata_do(MetadataClosure* f) { 2468 { 2469 // Visit all immediate references that are embedded in the instruction stream. 2470 RelocIterator iter(this, oops_reloc_begin()); 2471 while (iter.next()) { 2472 if (iter.type() == relocInfo::metadata_type) { 2473 metadata_Relocation* r = iter.metadata_reloc(); 2474 // In this metadata, we must only follow those metadatas directly embedded in 2475 // the code. Other metadatas (oop_index>0) are seen as part of 2476 // the metadata section below. 2477 assert(1 == (r->metadata_is_immediate()) + 2478 (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()), 2479 "metadata must be found in exactly one place"); 2480 if (r->metadata_is_immediate() && r->metadata_value() != nullptr) { 2481 Metadata* md = r->metadata_value(); 2482 if (md != _method) f->do_metadata(md); 2483 } 2484 } else if (iter.type() == relocInfo::virtual_call_type) { 2485 // Check compiledIC holders associated with this nmethod 2486 ResourceMark rm; 2487 CompiledIC *ic = CompiledIC_at(&iter); 2488 ic->metadata_do(f); 2489 } 2490 } 2491 } 2492 2493 // Visit the metadata section 2494 for (Metadata** p = metadata_begin(); p < metadata_end(); p++) { 2495 if (*p == Universe::non_oop_word() || *p == nullptr) continue; // skip non-oops 2496 Metadata* md = *p; 2497 f->do_metadata(md); 2498 } 2499 2500 // Visit metadata not embedded in the other places. 2501 if (_method != nullptr) f->do_metadata(_method); 2502 } 2503 2504 // Heuristic for nuking nmethods even though their oops are live. 2505 // Main purpose is to reduce code cache pressure and get rid of 2506 // nmethods that don't seem to be all that relevant any longer. 2507 bool nmethod::is_cold() { 2508 if (!MethodFlushing || is_native_method() || is_not_installed()) { 2509 // No heuristic unloading at all 2510 return false; 2511 } 2512 2513 if (!is_maybe_on_stack() && is_not_entrant()) { 2514 // Not entrant nmethods that are not on any stack can just 2515 // be removed 2516 return true; 2517 } 2518 2519 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod(); 2520 if (bs_nm == nullptr || !bs_nm->supports_entry_barrier(this)) { 2521 // On platforms that don't support nmethod entry barriers, we can't 2522 // trust the temporal aspect of the gc epochs. So we can't detect 2523 // cold nmethods on such platforms. 2524 return false; 2525 } 2526 2527 if (!UseCodeCacheFlushing) { 2528 // Bail out if we don't heuristically remove nmethods 2529 return false; 2530 } 2531 2532 // Other code can be phased out more gradually after N GCs 2533 return CodeCache::previous_completed_gc_marking_cycle() > _gc_epoch + 2 * CodeCache::cold_gc_count(); 2534 } 2535 2536 // The _is_unloading_state encodes a tuple comprising the unloading cycle 2537 // and the result of IsUnloadingBehaviour::is_unloading() for that cycle. 2538 // This is the bit layout of the _is_unloading_state byte: 00000CCU 2539 // CC refers to the cycle, which has 2 bits, and U refers to the result of 2540 // IsUnloadingBehaviour::is_unloading() for that unloading cycle. 2541 2542 class IsUnloadingState: public AllStatic { 2543 static const uint8_t _is_unloading_mask = 1; 2544 static const uint8_t _is_unloading_shift = 0; 2545 static const uint8_t _unloading_cycle_mask = 6; 2546 static const uint8_t _unloading_cycle_shift = 1; 2547 2548 static uint8_t set_is_unloading(uint8_t state, bool value) { 2549 state &= (uint8_t)~_is_unloading_mask; 2550 if (value) { 2551 state |= 1 << _is_unloading_shift; 2552 } 2553 assert(is_unloading(state) == value, "unexpected unloading cycle overflow"); 2554 return state; 2555 } 2556 2557 static uint8_t set_unloading_cycle(uint8_t state, uint8_t value) { 2558 state &= (uint8_t)~_unloading_cycle_mask; 2559 state |= (uint8_t)(value << _unloading_cycle_shift); 2560 assert(unloading_cycle(state) == value, "unexpected unloading cycle overflow"); 2561 return state; 2562 } 2563 2564 public: 2565 static bool is_unloading(uint8_t state) { return (state & _is_unloading_mask) >> _is_unloading_shift == 1; } 2566 static uint8_t unloading_cycle(uint8_t state) { return (state & _unloading_cycle_mask) >> _unloading_cycle_shift; } 2567 2568 static uint8_t create(bool is_unloading, uint8_t unloading_cycle) { 2569 uint8_t state = 0; 2570 state = set_is_unloading(state, is_unloading); 2571 state = set_unloading_cycle(state, unloading_cycle); 2572 return state; 2573 } 2574 }; 2575 2576 bool nmethod::is_unloading() { 2577 uint8_t state = Atomic::load(&_is_unloading_state); 2578 bool state_is_unloading = IsUnloadingState::is_unloading(state); 2579 if (state_is_unloading) { 2580 return true; 2581 } 2582 uint8_t state_unloading_cycle = IsUnloadingState::unloading_cycle(state); 2583 uint8_t current_cycle = CodeCache::unloading_cycle(); 2584 if (state_unloading_cycle == current_cycle) { 2585 return false; 2586 } 2587 2588 // The IsUnloadingBehaviour is responsible for calculating if the nmethod 2589 // should be unloaded. This can be either because there is a dead oop, 2590 // or because is_cold() heuristically determines it is time to unload. 2591 state_unloading_cycle = current_cycle; 2592 state_is_unloading = IsUnloadingBehaviour::is_unloading(this); 2593 uint8_t new_state = IsUnloadingState::create(state_is_unloading, state_unloading_cycle); 2594 2595 // Note that if an nmethod has dead oops, everyone will agree that the 2596 // nmethod is_unloading. However, the is_cold heuristics can yield 2597 // different outcomes, so we guard the computed result with a CAS 2598 // to ensure all threads have a shared view of whether an nmethod 2599 // is_unloading or not. 2600 uint8_t found_state = Atomic::cmpxchg(&_is_unloading_state, state, new_state, memory_order_relaxed); 2601 2602 if (found_state == state) { 2603 // First to change state, we win 2604 return state_is_unloading; 2605 } else { 2606 // State already set, so use it 2607 return IsUnloadingState::is_unloading(found_state); 2608 } 2609 } 2610 2611 void nmethod::clear_unloading_state() { 2612 uint8_t state = IsUnloadingState::create(false, CodeCache::unloading_cycle()); 2613 Atomic::store(&_is_unloading_state, state); 2614 } 2615 2616 2617 // This is called at the end of the strong tracing/marking phase of a 2618 // GC to unload an nmethod if it contains otherwise unreachable 2619 // oops or is heuristically found to be not important. 2620 void nmethod::do_unloading(bool unloading_occurred) { 2621 // Make sure the oop's ready to receive visitors 2622 if (is_unloading()) { 2623 unlink(); 2624 } else { 2625 unload_nmethod_caches(unloading_occurred); 2626 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod(); 2627 if (bs_nm != nullptr) { 2628 bs_nm->disarm(this); 2629 } 2630 } 2631 } 2632 2633 void nmethod::oops_do(OopClosure* f, bool allow_dead) { 2634 // Prevent extra code cache walk for platforms that don't have immediate oops. 2635 if (relocInfo::mustIterateImmediateOopsInCode()) { 2636 RelocIterator iter(this, oops_reloc_begin()); 2637 2638 while (iter.next()) { 2639 if (iter.type() == relocInfo::oop_type ) { 2640 oop_Relocation* r = iter.oop_reloc(); 2641 // In this loop, we must only follow those oops directly embedded in 2642 // the code. Other oops (oop_index>0) are seen as part of scopes_oops. 2643 assert(1 == (r->oop_is_immediate()) + 2644 (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()), 2645 "oop must be found in exactly one place"); 2646 if (r->oop_is_immediate() && r->oop_value() != nullptr) { 2647 f->do_oop(r->oop_addr()); 2648 } 2649 } 2650 } 2651 } 2652 2653 // Scopes 2654 // This includes oop constants not inlined in the code stream. 2655 for (oop* p = oops_begin(); p < oops_end(); p++) { 2656 if (*p == Universe::non_oop_word()) continue; // skip non-oops 2657 f->do_oop(p); 2658 } 2659 } 2660 2661 void nmethod::follow_nmethod(OopIterateClosure* cl) { 2662 // Process oops in the nmethod 2663 oops_do(cl); 2664 2665 // CodeCache unloading support 2666 mark_as_maybe_on_stack(); 2667 2668 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod(); 2669 bs_nm->disarm(this); 2670 2671 // There's an assumption made that this function is not used by GCs that 2672 // relocate objects, and therefore we don't call fix_oop_relocations. 2673 } 2674 2675 nmethod* volatile nmethod::_oops_do_mark_nmethods; 2676 2677 void nmethod::oops_do_log_change(const char* state) { 2678 LogTarget(Trace, gc, nmethod) lt; 2679 if (lt.is_enabled()) { 2680 LogStream ls(lt); 2681 CompileTask::print(&ls, this, state, true /* short_form */); 2682 } 2683 } 2684 2685 bool nmethod::oops_do_try_claim() { 2686 if (oops_do_try_claim_weak_request()) { 2687 nmethod* result = oops_do_try_add_to_list_as_weak_done(); 2688 assert(result == nullptr, "adding to global list as weak done must always succeed."); 2689 return true; 2690 } 2691 return false; 2692 } 2693 2694 bool nmethod::oops_do_try_claim_weak_request() { 2695 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint"); 2696 2697 if ((_oops_do_mark_link == nullptr) && 2698 (Atomic::replace_if_null(&_oops_do_mark_link, mark_link(this, claim_weak_request_tag)))) { 2699 oops_do_log_change("oops_do, mark weak request"); 2700 return true; 2701 } 2702 return false; 2703 } 2704 2705 void nmethod::oops_do_set_strong_done(nmethod* old_head) { 2706 _oops_do_mark_link = mark_link(old_head, claim_strong_done_tag); 2707 } 2708 2709 nmethod::oops_do_mark_link* nmethod::oops_do_try_claim_strong_done() { 2710 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint"); 2711 2712 oops_do_mark_link* old_next = Atomic::cmpxchg(&_oops_do_mark_link, mark_link(nullptr, claim_weak_request_tag), mark_link(this, claim_strong_done_tag)); 2713 if (old_next == nullptr) { 2714 oops_do_log_change("oops_do, mark strong done"); 2715 } 2716 return old_next; 2717 } 2718 2719 nmethod::oops_do_mark_link* nmethod::oops_do_try_add_strong_request(nmethod::oops_do_mark_link* next) { 2720 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint"); 2721 assert(next == mark_link(this, claim_weak_request_tag), "Should be claimed as weak"); 2722 2723 oops_do_mark_link* old_next = Atomic::cmpxchg(&_oops_do_mark_link, next, mark_link(this, claim_strong_request_tag)); 2724 if (old_next == next) { 2725 oops_do_log_change("oops_do, mark strong request"); 2726 } 2727 return old_next; 2728 } 2729 2730 bool nmethod::oops_do_try_claim_weak_done_as_strong_done(nmethod::oops_do_mark_link* next) { 2731 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint"); 2732 assert(extract_state(next) == claim_weak_done_tag, "Should be claimed as weak done"); 2733 2734 oops_do_mark_link* old_next = Atomic::cmpxchg(&_oops_do_mark_link, next, mark_link(extract_nmethod(next), claim_strong_done_tag)); 2735 if (old_next == next) { 2736 oops_do_log_change("oops_do, mark weak done -> mark strong done"); 2737 return true; 2738 } 2739 return false; 2740 } 2741 2742 nmethod* nmethod::oops_do_try_add_to_list_as_weak_done() { 2743 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint"); 2744 2745 assert(extract_state(_oops_do_mark_link) == claim_weak_request_tag || 2746 extract_state(_oops_do_mark_link) == claim_strong_request_tag, 2747 "must be but is nmethod " PTR_FORMAT " %u", p2i(extract_nmethod(_oops_do_mark_link)), extract_state(_oops_do_mark_link)); 2748 2749 nmethod* old_head = Atomic::xchg(&_oops_do_mark_nmethods, this); 2750 // Self-loop if needed. 2751 if (old_head == nullptr) { 2752 old_head = this; 2753 } 2754 // Try to install end of list and weak done tag. 2755 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)) { 2756 oops_do_log_change("oops_do, mark weak done"); 2757 return nullptr; 2758 } else { 2759 return old_head; 2760 } 2761 } 2762 2763 void nmethod::oops_do_add_to_list_as_strong_done() { 2764 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint"); 2765 2766 nmethod* old_head = Atomic::xchg(&_oops_do_mark_nmethods, this); 2767 // Self-loop if needed. 2768 if (old_head == nullptr) { 2769 old_head = this; 2770 } 2771 assert(_oops_do_mark_link == mark_link(this, claim_strong_done_tag), "must be but is nmethod " PTR_FORMAT " state %u", 2772 p2i(extract_nmethod(_oops_do_mark_link)), extract_state(_oops_do_mark_link)); 2773 2774 oops_do_set_strong_done(old_head); 2775 } 2776 2777 void nmethod::oops_do_process_weak(OopsDoProcessor* p) { 2778 if (!oops_do_try_claim_weak_request()) { 2779 // Failed to claim for weak processing. 2780 oops_do_log_change("oops_do, mark weak request fail"); 2781 return; 2782 } 2783 2784 p->do_regular_processing(this); 2785 2786 nmethod* old_head = oops_do_try_add_to_list_as_weak_done(); 2787 if (old_head == nullptr) { 2788 return; 2789 } 2790 oops_do_log_change("oops_do, mark weak done fail"); 2791 // Adding to global list failed, another thread added a strong request. 2792 assert(extract_state(_oops_do_mark_link) == claim_strong_request_tag, 2793 "must be but is %u", extract_state(_oops_do_mark_link)); 2794 2795 oops_do_log_change("oops_do, mark weak request -> mark strong done"); 2796 2797 oops_do_set_strong_done(old_head); 2798 // Do missing strong processing. 2799 p->do_remaining_strong_processing(this); 2800 } 2801 2802 void nmethod::oops_do_process_strong(OopsDoProcessor* p) { 2803 oops_do_mark_link* next_raw = oops_do_try_claim_strong_done(); 2804 if (next_raw == nullptr) { 2805 p->do_regular_processing(this); 2806 oops_do_add_to_list_as_strong_done(); 2807 return; 2808 } 2809 // Claim failed. Figure out why and handle it. 2810 if (oops_do_has_weak_request(next_raw)) { 2811 oops_do_mark_link* old = next_raw; 2812 // Claim failed because being weak processed (state == "weak request"). 2813 // Try to request deferred strong processing. 2814 next_raw = oops_do_try_add_strong_request(old); 2815 if (next_raw == old) { 2816 // Successfully requested deferred strong processing. 2817 return; 2818 } 2819 // Failed because of a concurrent transition. No longer in "weak request" state. 2820 } 2821 if (oops_do_has_any_strong_state(next_raw)) { 2822 // Already claimed for strong processing or requested for such. 2823 return; 2824 } 2825 if (oops_do_try_claim_weak_done_as_strong_done(next_raw)) { 2826 // Successfully claimed "weak done" as "strong done". Do the missing marking. 2827 p->do_remaining_strong_processing(this); 2828 return; 2829 } 2830 // Claim failed, some other thread got it. 2831 } 2832 2833 void nmethod::oops_do_marking_prologue() { 2834 assert_at_safepoint(); 2835 2836 log_trace(gc, nmethod)("oops_do_marking_prologue"); 2837 assert(_oops_do_mark_nmethods == nullptr, "must be empty"); 2838 } 2839 2840 void nmethod::oops_do_marking_epilogue() { 2841 assert_at_safepoint(); 2842 2843 nmethod* next = _oops_do_mark_nmethods; 2844 _oops_do_mark_nmethods = nullptr; 2845 if (next != nullptr) { 2846 nmethod* cur; 2847 do { 2848 cur = next; 2849 next = extract_nmethod(cur->_oops_do_mark_link); 2850 cur->_oops_do_mark_link = nullptr; 2851 DEBUG_ONLY(cur->verify_oop_relocations()); 2852 2853 LogTarget(Trace, gc, nmethod) lt; 2854 if (lt.is_enabled()) { 2855 LogStream ls(lt); 2856 CompileTask::print(&ls, cur, "oops_do, unmark", /*short_form:*/ true); 2857 } 2858 // End if self-loop has been detected. 2859 } while (cur != next); 2860 } 2861 log_trace(gc, nmethod)("oops_do_marking_epilogue"); 2862 } 2863 2864 inline bool includes(void* p, void* from, void* to) { 2865 return from <= p && p < to; 2866 } 2867 2868 2869 void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) { 2870 assert(count >= 2, "must be sentinel values, at least"); 2871 2872 #ifdef ASSERT 2873 // must be sorted and unique; we do a binary search in find_pc_desc() 2874 int prev_offset = pcs[0].pc_offset(); 2875 assert(prev_offset == PcDesc::lower_offset_limit, 2876 "must start with a sentinel"); 2877 for (int i = 1; i < count; i++) { 2878 int this_offset = pcs[i].pc_offset(); 2879 assert(this_offset > prev_offset, "offsets must be sorted"); 2880 prev_offset = this_offset; 2881 } 2882 assert(prev_offset == PcDesc::upper_offset_limit, 2883 "must end with a sentinel"); 2884 #endif //ASSERT 2885 2886 // Search for MethodHandle invokes and tag the nmethod. 2887 for (int i = 0; i < count; i++) { 2888 if (pcs[i].is_method_handle_invoke()) { 2889 set_has_method_handle_invokes(true); 2890 break; 2891 } 2892 } 2893 assert(has_method_handle_invokes() == (_deopt_mh_handler_offset != -1), "must have deopt mh handler"); 2894 2895 int size = count * sizeof(PcDesc); 2896 assert(scopes_pcs_size() >= size, "oob"); 2897 memcpy(scopes_pcs_begin(), pcs, size); 2898 2899 // Adjust the final sentinel downward. 2900 PcDesc* last_pc = &scopes_pcs_begin()[count-1]; 2901 assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity"); 2902 last_pc->set_pc_offset(content_size() + 1); 2903 for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) { 2904 // Fill any rounding gaps with copies of the last record. 2905 last_pc[1] = last_pc[0]; 2906 } 2907 // The following assert could fail if sizeof(PcDesc) is not 2908 // an integral multiple of oopSize (the rounding term). 2909 // If it fails, change the logic to always allocate a multiple 2910 // of sizeof(PcDesc), and fill unused words with copies of *last_pc. 2911 assert(last_pc + 1 == scopes_pcs_end(), "must match exactly"); 2912 } 2913 2914 void nmethod::copy_scopes_data(u_char* buffer, int size) { 2915 assert(scopes_data_size() >= size, "oob"); 2916 memcpy(scopes_data_begin(), buffer, size); 2917 } 2918 2919 #ifdef ASSERT 2920 static PcDesc* linear_search(int pc_offset, bool approximate, PcDesc* lower, PcDesc* upper) { 2921 PcDesc* res = nullptr; 2922 assert(lower != nullptr && lower->pc_offset() == PcDesc::lower_offset_limit, 2923 "must start with a sentinel"); 2924 // lower + 1 to exclude initial sentinel 2925 for (PcDesc* p = lower + 1; p < upper; p++) { 2926 NOT_PRODUCT(--pc_nmethod_stats.pc_desc_tests); // don't count this call to match_desc 2927 if (match_desc(p, pc_offset, approximate)) { 2928 if (res == nullptr) { 2929 res = p; 2930 } else { 2931 res = (PcDesc*) badAddress; 2932 } 2933 } 2934 } 2935 return res; 2936 } 2937 #endif 2938 2939 2940 #ifndef PRODUCT 2941 // Version of method to collect statistic 2942 PcDesc* PcDescContainer::find_pc_desc(address pc, bool approximate, address code_begin, 2943 PcDesc* lower, PcDesc* upper) { 2944 ++pc_nmethod_stats.pc_desc_queries; 2945 if (approximate) ++pc_nmethod_stats.pc_desc_approx; 2946 2947 PcDesc* desc = _pc_desc_cache.last_pc_desc(); 2948 assert(desc != nullptr, "PcDesc cache should be initialized already"); 2949 if (desc->pc_offset() == (pc - code_begin)) { 2950 // Cached value matched 2951 ++pc_nmethod_stats.pc_desc_tests; 2952 ++pc_nmethod_stats.pc_desc_repeats; 2953 return desc; 2954 } 2955 return find_pc_desc_internal(pc, approximate, code_begin, lower, upper); 2956 } 2957 #endif 2958 2959 // Finds a PcDesc with real-pc equal to "pc" 2960 PcDesc* PcDescContainer::find_pc_desc_internal(address pc, bool approximate, address code_begin, 2961 PcDesc* lower_incl, PcDesc* upper_incl) { 2962 if ((pc < code_begin) || 2963 (pc - code_begin) >= (ptrdiff_t) PcDesc::upper_offset_limit) { 2964 return nullptr; // PC is wildly out of range 2965 } 2966 int pc_offset = (int) (pc - code_begin); 2967 2968 // Check the PcDesc cache if it contains the desired PcDesc 2969 // (This as an almost 100% hit rate.) 2970 PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate); 2971 if (res != nullptr) { 2972 assert(res == linear_search(pc_offset, approximate, lower_incl, upper_incl), "cache ok"); 2973 return res; 2974 } 2975 2976 // Fallback algorithm: quasi-linear search for the PcDesc 2977 // Find the last pc_offset less than the given offset. 2978 // The successor must be the required match, if there is a match at all. 2979 // (Use a fixed radix to avoid expensive affine pointer arithmetic.) 2980 PcDesc* lower = lower_incl; // this is initial sentinel 2981 PcDesc* upper = upper_incl - 1; // exclude final sentinel 2982 if (lower >= upper) return nullptr; // no PcDescs at all 2983 2984 #define assert_LU_OK \ 2985 /* invariant on lower..upper during the following search: */ \ 2986 assert(lower->pc_offset() < pc_offset, "sanity"); \ 2987 assert(upper->pc_offset() >= pc_offset, "sanity") 2988 assert_LU_OK; 2989 2990 // Use the last successful return as a split point. 2991 PcDesc* mid = _pc_desc_cache.last_pc_desc(); 2992 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches); 2993 if (mid->pc_offset() < pc_offset) { 2994 lower = mid; 2995 } else { 2996 upper = mid; 2997 } 2998 2999 // Take giant steps at first (4096, then 256, then 16, then 1) 3000 const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ DEBUG_ONLY(-1); 3001 const int RADIX = (1 << LOG2_RADIX); 3002 for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) { 3003 while ((mid = lower + step) < upper) { 3004 assert_LU_OK; 3005 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches); 3006 if (mid->pc_offset() < pc_offset) { 3007 lower = mid; 3008 } else { 3009 upper = mid; 3010 break; 3011 } 3012 } 3013 assert_LU_OK; 3014 } 3015 3016 // Sneak up on the value with a linear search of length ~16. 3017 while (true) { 3018 assert_LU_OK; 3019 mid = lower + 1; 3020 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches); 3021 if (mid->pc_offset() < pc_offset) { 3022 lower = mid; 3023 } else { 3024 upper = mid; 3025 break; 3026 } 3027 } 3028 #undef assert_LU_OK 3029 3030 if (match_desc(upper, pc_offset, approximate)) { 3031 assert(upper == linear_search(pc_offset, approximate, lower_incl, upper_incl), "search mismatch"); 3032 if (!Thread::current_in_asgct()) { 3033 // we don't want to modify the cache if we're in ASGCT 3034 // which is typically called in a signal handler 3035 _pc_desc_cache.add_pc_desc(upper); 3036 } 3037 return upper; 3038 } else { 3039 assert(nullptr == linear_search(pc_offset, approximate, lower_incl, upper_incl), "search mismatch"); 3040 return nullptr; 3041 } 3042 } 3043 3044 bool nmethod::check_dependency_on(DepChange& changes) { 3045 // What has happened: 3046 // 1) a new class dependee has been added 3047 // 2) dependee and all its super classes have been marked 3048 bool found_check = false; // set true if we are upset 3049 for (Dependencies::DepStream deps(this); deps.next(); ) { 3050 // Evaluate only relevant dependencies. 3051 if (deps.spot_check_dependency_at(changes) != nullptr) { 3052 found_check = true; 3053 NOT_DEBUG(break); 3054 } 3055 } 3056 return found_check; 3057 } 3058 3059 // Called from mark_for_deoptimization, when dependee is invalidated. 3060 bool nmethod::is_dependent_on_method(Method* dependee) { 3061 for (Dependencies::DepStream deps(this); deps.next(); ) { 3062 if (deps.type() != Dependencies::evol_method) 3063 continue; 3064 Method* method = deps.method_argument(0); 3065 if (method == dependee) return true; 3066 } 3067 return false; 3068 } 3069 3070 void nmethod_init() { 3071 // make sure you didn't forget to adjust the filler fields 3072 assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word"); 3073 } 3074 3075 // ----------------------------------------------------------------------------- 3076 // Verification 3077 3078 class VerifyOopsClosure: public OopClosure { 3079 nmethod* _nm; 3080 bool _ok; 3081 public: 3082 VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { } 3083 bool ok() { return _ok; } 3084 virtual void do_oop(oop* p) { 3085 if (oopDesc::is_oop_or_null(*p)) return; 3086 // Print diagnostic information before calling print_nmethod(). 3087 // Assertions therein might prevent call from returning. 3088 tty->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)", 3089 p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm)); 3090 if (_ok) { 3091 _nm->print_nmethod(true); 3092 _ok = false; 3093 } 3094 } 3095 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); } 3096 }; 3097 3098 class VerifyMetadataClosure: public MetadataClosure { 3099 public: 3100 void do_metadata(Metadata* md) { 3101 if (md->is_method()) { 3102 Method* method = (Method*)md; 3103 assert(!method->is_old(), "Should not be installing old methods"); 3104 } 3105 } 3106 }; 3107 3108 3109 void nmethod::verify() { 3110 if (is_not_entrant()) 3111 return; 3112 3113 // Make sure all the entry points are correctly aligned for patching. 3114 NativeJump::check_verified_entry_alignment(entry_point(), verified_entry_point()); 3115 3116 // assert(oopDesc::is_oop(method()), "must be valid"); 3117 3118 ResourceMark rm; 3119 3120 if (!CodeCache::contains(this)) { 3121 fatal("nmethod at " INTPTR_FORMAT " not in zone", p2i(this)); 3122 } 3123 3124 if(is_native_method() ) 3125 return; 3126 3127 nmethod* nm = CodeCache::find_nmethod(verified_entry_point()); 3128 if (nm != this) { 3129 fatal("find_nmethod did not find this nmethod (" INTPTR_FORMAT ")", p2i(this)); 3130 } 3131 3132 // Verification can triggered during shutdown after AOTCodeCache is closed. 3133 // If the Scopes data is in the AOT code cache, then we should avoid verification during shutdown. 3134 if (!is_aot() || AOTCodeCache::is_on()) { 3135 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) { 3136 if (! p->verify(this)) { 3137 tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", p2i(this)); 3138 } 3139 } 3140 3141 #ifdef ASSERT 3142 #if INCLUDE_JVMCI 3143 { 3144 // Verify that implicit exceptions that deoptimize have a PcDesc and OopMap 3145 ImmutableOopMapSet* oms = oop_maps(); 3146 ImplicitExceptionTable implicit_table(this); 3147 for (uint i = 0; i < implicit_table.len(); i++) { 3148 int exec_offset = (int) implicit_table.get_exec_offset(i); 3149 if (implicit_table.get_exec_offset(i) == implicit_table.get_cont_offset(i)) { 3150 assert(pc_desc_at(code_begin() + exec_offset) != nullptr, "missing PcDesc"); 3151 bool found = false; 3152 for (int i = 0, imax = oms->count(); i < imax; i++) { 3153 if (oms->pair_at(i)->pc_offset() == exec_offset) { 3154 found = true; 3155 break; 3156 } 3157 } 3158 assert(found, "missing oopmap"); 3159 } 3160 } 3161 } 3162 #endif 3163 #endif 3164 } 3165 3166 VerifyOopsClosure voc(this); 3167 oops_do(&voc); 3168 assert(voc.ok(), "embedded oops must be OK"); 3169 Universe::heap()->verify_nmethod(this); 3170 3171 assert(_oops_do_mark_link == nullptr, "_oops_do_mark_link for %s should be nullptr but is " PTR_FORMAT, 3172 nm->method()->external_name(), p2i(_oops_do_mark_link)); 3173 if (!is_aot() || AOTCodeCache::is_on()) { 3174 verify_scopes(); 3175 } 3176 3177 CompiledICLocker nm_verify(this); 3178 VerifyMetadataClosure vmc; 3179 metadata_do(&vmc); 3180 } 3181 3182 3183 void nmethod::verify_interrupt_point(address call_site, bool is_inline_cache) { 3184 3185 // Verify IC only when nmethod installation is finished. 3186 if (!is_not_installed()) { 3187 if (CompiledICLocker::is_safe(this)) { 3188 if (is_inline_cache) { 3189 CompiledIC_at(this, call_site); 3190 } else { 3191 CompiledDirectCall::at(call_site); 3192 } 3193 } else { 3194 CompiledICLocker ml_verify(this); 3195 if (is_inline_cache) { 3196 CompiledIC_at(this, call_site); 3197 } else { 3198 CompiledDirectCall::at(call_site); 3199 } 3200 } 3201 } 3202 3203 HandleMark hm(Thread::current()); 3204 3205 PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address()); 3206 assert(pd != nullptr, "PcDesc must exist"); 3207 for (ScopeDesc* sd = new ScopeDesc(this, pd); 3208 !sd->is_top(); sd = sd->sender()) { 3209 sd->verify(); 3210 } 3211 } 3212 3213 void nmethod::verify_scopes() { 3214 if( !method() ) return; // Runtime stubs have no scope 3215 if (method()->is_native()) return; // Ignore stub methods. 3216 // iterate through all interrupt point 3217 // and verify the debug information is valid. 3218 RelocIterator iter(this); 3219 while (iter.next()) { 3220 address stub = nullptr; 3221 switch (iter.type()) { 3222 case relocInfo::virtual_call_type: 3223 verify_interrupt_point(iter.addr(), true /* is_inline_cache */); 3224 break; 3225 case relocInfo::opt_virtual_call_type: 3226 stub = iter.opt_virtual_call_reloc()->static_stub(); 3227 verify_interrupt_point(iter.addr(), false /* is_inline_cache */); 3228 break; 3229 case relocInfo::static_call_type: 3230 stub = iter.static_call_reloc()->static_stub(); 3231 verify_interrupt_point(iter.addr(), false /* is_inline_cache */); 3232 break; 3233 case relocInfo::runtime_call_type: 3234 case relocInfo::runtime_call_w_cp_type: { 3235 address destination = iter.reloc()->value(); 3236 // Right now there is no way to find out which entries support 3237 // an interrupt point. It would be nice if we had this 3238 // information in a table. 3239 break; 3240 } 3241 default: 3242 break; 3243 } 3244 assert(stub == nullptr || stub_contains(stub), "static call stub outside stub section"); 3245 } 3246 } 3247 3248 3249 // ----------------------------------------------------------------------------- 3250 // Printing operations 3251 3252 void nmethod::print_on_impl(outputStream* st) const { 3253 ResourceMark rm; 3254 3255 st->print("Compiled method "); 3256 3257 if (is_compiled_by_c1()) { 3258 st->print("(c1) "); 3259 } else if (is_compiled_by_c2()) { 3260 st->print("(c2) "); 3261 } else if (is_compiled_by_jvmci()) { 3262 st->print("(JVMCI) "); 3263 } else { 3264 st->print("(n/a) "); 3265 } 3266 3267 print_on_with_msg(st, nullptr); 3268 3269 if (WizardMode) { 3270 st->print("((nmethod*) " INTPTR_FORMAT ") ", p2i(this)); 3271 st->print(" for method " INTPTR_FORMAT , p2i(method())); 3272 st->print(" { "); 3273 st->print_cr("%s ", state()); 3274 st->print_cr("}:"); 3275 } 3276 if (size () > 0) st->print_cr(" total in heap [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 3277 p2i(this), 3278 p2i(this) + size(), 3279 size()); 3280 if (consts_size () > 0) st->print_cr(" constants [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 3281 p2i(consts_begin()), 3282 p2i(consts_end()), 3283 consts_size()); 3284 if (insts_size () > 0) st->print_cr(" main code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 3285 p2i(insts_begin()), 3286 p2i(insts_end()), 3287 insts_size()); 3288 if (stub_size () > 0) st->print_cr(" stub code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 3289 p2i(stub_begin()), 3290 p2i(stub_end()), 3291 stub_size()); 3292 if (oops_size () > 0) st->print_cr(" oops [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 3293 p2i(oops_begin()), 3294 p2i(oops_end()), 3295 oops_size()); 3296 if (mutable_data_size() > 0) st->print_cr(" mutable data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 3297 p2i(mutable_data_begin()), 3298 p2i(mutable_data_end()), 3299 mutable_data_size()); 3300 if (relocation_size() > 0) st->print_cr(" relocation [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 3301 p2i(relocation_begin()), 3302 p2i(relocation_end()), 3303 relocation_size()); 3304 if (metadata_size () > 0) st->print_cr(" metadata [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 3305 p2i(metadata_begin()), 3306 p2i(metadata_end()), 3307 metadata_size()); 3308 #if INCLUDE_JVMCI 3309 if (jvmci_data_size () > 0) st->print_cr(" JVMCI data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 3310 p2i(jvmci_data_begin()), 3311 p2i(jvmci_data_end()), 3312 jvmci_data_size()); 3313 #endif 3314 if (immutable_data_size() > 0) st->print_cr(" immutable data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 3315 p2i(immutable_data_begin()), 3316 p2i(immutable_data_end()), 3317 immutable_data_size()); 3318 if (dependencies_size () > 0) st->print_cr(" dependencies [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 3319 p2i(dependencies_begin()), 3320 p2i(dependencies_end()), 3321 dependencies_size()); 3322 if (nul_chk_table_size() > 0) st->print_cr(" nul chk table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 3323 p2i(nul_chk_table_begin()), 3324 p2i(nul_chk_table_end()), 3325 nul_chk_table_size()); 3326 if (handler_table_size() > 0) st->print_cr(" handler table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 3327 p2i(handler_table_begin()), 3328 p2i(handler_table_end()), 3329 handler_table_size()); 3330 if (scopes_pcs_size () > 0) st->print_cr(" scopes pcs [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 3331 p2i(scopes_pcs_begin()), 3332 p2i(scopes_pcs_end()), 3333 scopes_pcs_size()); 3334 if (scopes_data_size () > 0) st->print_cr(" scopes data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 3335 p2i(scopes_data_begin()), 3336 p2i(scopes_data_end()), 3337 scopes_data_size()); 3338 #if INCLUDE_JVMCI 3339 if (speculations_size () > 0) st->print_cr(" speculations [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 3340 p2i(speculations_begin()), 3341 p2i(speculations_end()), 3342 speculations_size()); 3343 #endif 3344 if (AOTCodeCache::is_on() && _aot_code_entry != nullptr) { 3345 _aot_code_entry->print(st); 3346 } 3347 } 3348 3349 void nmethod::print_code() { 3350 ResourceMark m; 3351 ttyLocker ttyl; 3352 // Call the specialized decode method of this class. 3353 decode(tty); 3354 } 3355 3356 #ifndef PRODUCT // called InstanceKlass methods are available only then. Declared as PRODUCT_RETURN 3357 3358 void nmethod::print_dependencies_on(outputStream* out) { 3359 ResourceMark rm; 3360 stringStream st; 3361 st.print_cr("Dependencies:"); 3362 for (Dependencies::DepStream deps(this); deps.next(); ) { 3363 deps.print_dependency(&st); 3364 InstanceKlass* ctxk = deps.context_type(); 3365 if (ctxk != nullptr) { 3366 if (ctxk->is_dependent_nmethod(this)) { 3367 st.print_cr(" [nmethod<=klass]%s", ctxk->external_name()); 3368 } 3369 } 3370 deps.log_dependency(); // put it into the xml log also 3371 } 3372 out->print_raw(st.as_string()); 3373 } 3374 #endif 3375 3376 #if defined(SUPPORT_DATA_STRUCTS) 3377 3378 // Print the oops from the underlying CodeBlob. 3379 void nmethod::print_oops(outputStream* st) { 3380 ResourceMark m; 3381 st->print("Oops:"); 3382 if (oops_begin() < oops_end()) { 3383 st->cr(); 3384 for (oop* p = oops_begin(); p < oops_end(); p++) { 3385 Disassembler::print_location((unsigned char*)p, (unsigned char*)oops_begin(), (unsigned char*)oops_end(), st, true, false); 3386 st->print(PTR_FORMAT " ", *((uintptr_t*)p)); 3387 if (Universe::contains_non_oop_word(p)) { 3388 st->print_cr("NON_OOP"); 3389 continue; // skip non-oops 3390 } 3391 if (*p == nullptr) { 3392 st->print_cr("nullptr-oop"); 3393 continue; // skip non-oops 3394 } 3395 (*p)->print_value_on(st); 3396 st->cr(); 3397 } 3398 } else { 3399 st->print_cr(" <list empty>"); 3400 } 3401 } 3402 3403 // Print metadata pool. 3404 void nmethod::print_metadata(outputStream* st) { 3405 ResourceMark m; 3406 st->print("Metadata:"); 3407 if (metadata_begin() < metadata_end()) { 3408 st->cr(); 3409 for (Metadata** p = metadata_begin(); p < metadata_end(); p++) { 3410 Disassembler::print_location((unsigned char*)p, (unsigned char*)metadata_begin(), (unsigned char*)metadata_end(), st, true, false); 3411 st->print(PTR_FORMAT " ", *((uintptr_t*)p)); 3412 if (*p && *p != Universe::non_oop_word()) { 3413 (*p)->print_value_on(st); 3414 } 3415 st->cr(); 3416 } 3417 } else { 3418 st->print_cr(" <list empty>"); 3419 } 3420 } 3421 3422 #ifndef PRODUCT // ScopeDesc::print_on() is available only then. Declared as PRODUCT_RETURN 3423 void nmethod::print_scopes_on(outputStream* st) { 3424 // Find the first pc desc for all scopes in the code and print it. 3425 ResourceMark rm; 3426 st->print("scopes:"); 3427 if (scopes_pcs_begin() < scopes_pcs_end()) { 3428 st->cr(); 3429 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) { 3430 if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null) 3431 continue; 3432 3433 ScopeDesc* sd = scope_desc_at(p->real_pc(this)); 3434 while (sd != nullptr) { 3435 sd->print_on(st, p); // print output ends with a newline 3436 sd = sd->sender(); 3437 } 3438 } 3439 } else { 3440 st->print_cr(" <list empty>"); 3441 } 3442 } 3443 #endif 3444 3445 #ifndef PRODUCT // RelocIterator does support printing only then. 3446 void nmethod::print_relocations_on(outputStream* st) { 3447 ResourceMark m; // in case methods get printed via the debugger 3448 st->print_cr("relocations:"); 3449 RelocIterator iter(this); 3450 iter.print_on(st); 3451 } 3452 #endif 3453 3454 void nmethod::print_pcs_on(outputStream* st) { 3455 ResourceMark m; // in case methods get printed via debugger 3456 st->print("pc-bytecode offsets:"); 3457 if (scopes_pcs_begin() < scopes_pcs_end()) { 3458 st->cr(); 3459 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) { 3460 p->print_on(st, this); // print output ends with a newline 3461 } 3462 } else { 3463 st->print_cr(" <list empty>"); 3464 } 3465 } 3466 3467 void nmethod::print_handler_table() { 3468 ExceptionHandlerTable(this).print(code_begin()); 3469 } 3470 3471 void nmethod::print_nul_chk_table() { 3472 ImplicitExceptionTable(this).print(code_begin()); 3473 } 3474 3475 void nmethod::print_recorded_oop(int log_n, int i) { 3476 void* value; 3477 3478 if (i == 0) { 3479 value = nullptr; 3480 } else { 3481 // Be careful around non-oop words. Don't create an oop 3482 // with that value, or it will assert in verification code. 3483 if (Universe::contains_non_oop_word(oop_addr_at(i))) { 3484 value = Universe::non_oop_word(); 3485 } else { 3486 value = oop_at(i); 3487 } 3488 } 3489 3490 tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(value)); 3491 3492 if (value == Universe::non_oop_word()) { 3493 tty->print("non-oop word"); 3494 } else { 3495 if (value == nullptr) { 3496 tty->print("nullptr-oop"); 3497 } else { 3498 oop_at(i)->print_value_on(tty); 3499 } 3500 } 3501 3502 tty->cr(); 3503 } 3504 3505 void nmethod::print_recorded_oops() { 3506 const int n = oops_count(); 3507 const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6; 3508 tty->print("Recorded oops:"); 3509 if (n > 0) { 3510 tty->cr(); 3511 for (int i = 0; i < n; i++) { 3512 print_recorded_oop(log_n, i); 3513 } 3514 } else { 3515 tty->print_cr(" <list empty>"); 3516 } 3517 } 3518 3519 void nmethod::print_recorded_metadata() { 3520 const int n = metadata_count(); 3521 const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6; 3522 tty->print("Recorded metadata:"); 3523 if (n > 0) { 3524 tty->cr(); 3525 for (int i = 0; i < n; i++) { 3526 Metadata* m = metadata_at(i); 3527 tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(m)); 3528 if (m == (Metadata*)Universe::non_oop_word()) { 3529 tty->print("non-metadata word"); 3530 } else if (m == nullptr) { 3531 tty->print("nullptr-oop"); 3532 } else { 3533 Metadata::print_value_on_maybe_null(tty, m); 3534 } 3535 tty->cr(); 3536 } 3537 } else { 3538 tty->print_cr(" <list empty>"); 3539 } 3540 } 3541 #endif 3542 3543 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY) 3544 3545 void nmethod::print_constant_pool(outputStream* st) { 3546 //----------------------------------- 3547 //---< Print the constant pool >--- 3548 //----------------------------------- 3549 int consts_size = this->consts_size(); 3550 if ( consts_size > 0 ) { 3551 unsigned char* cstart = this->consts_begin(); 3552 unsigned char* cp = cstart; 3553 unsigned char* cend = cp + consts_size; 3554 unsigned int bytes_per_line = 4; 3555 unsigned int CP_alignment = 8; 3556 unsigned int n; 3557 3558 st->cr(); 3559 3560 //---< print CP header to make clear what's printed >--- 3561 if( ((uintptr_t)cp&(CP_alignment-1)) == 0 ) { 3562 n = bytes_per_line; 3563 st->print_cr("[Constant Pool]"); 3564 Disassembler::print_location(cp, cstart, cend, st, true, true); 3565 Disassembler::print_hexdata(cp, n, st, true); 3566 st->cr(); 3567 } else { 3568 n = (int)((uintptr_t)cp & (bytes_per_line-1)); 3569 st->print_cr("[Constant Pool (unaligned)]"); 3570 } 3571 3572 //---< print CP contents, bytes_per_line at a time >--- 3573 while (cp < cend) { 3574 Disassembler::print_location(cp, cstart, cend, st, true, false); 3575 Disassembler::print_hexdata(cp, n, st, false); 3576 cp += n; 3577 n = bytes_per_line; 3578 st->cr(); 3579 } 3580 3581 //---< Show potential alignment gap between constant pool and code >--- 3582 cend = code_begin(); 3583 if( cp < cend ) { 3584 n = 4; 3585 st->print_cr("[Code entry alignment]"); 3586 while (cp < cend) { 3587 Disassembler::print_location(cp, cstart, cend, st, false, false); 3588 cp += n; 3589 st->cr(); 3590 } 3591 } 3592 } else { 3593 st->print_cr("[Constant Pool (empty)]"); 3594 } 3595 st->cr(); 3596 } 3597 3598 #endif 3599 3600 // Disassemble this nmethod. 3601 // Print additional debug information, if requested. This could be code 3602 // comments, block comments, profiling counters, etc. 3603 // The undisassembled format is useful no disassembler library is available. 3604 // The resulting hex dump (with markers) can be disassembled later, or on 3605 // another system, when/where a disassembler library is available. 3606 void nmethod::decode2(outputStream* ost) const { 3607 3608 // Called from frame::back_trace_with_decode without ResourceMark. 3609 ResourceMark rm; 3610 3611 // Make sure we have a valid stream to print on. 3612 outputStream* st = ost ? ost : tty; 3613 3614 #if defined(SUPPORT_ABSTRACT_ASSEMBLY) && ! defined(SUPPORT_ASSEMBLY) 3615 const bool use_compressed_format = true; 3616 const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() || 3617 AbstractDisassembler::show_block_comment()); 3618 #else 3619 const bool use_compressed_format = Disassembler::is_abstract(); 3620 const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() || 3621 AbstractDisassembler::show_block_comment()); 3622 #endif 3623 3624 st->cr(); 3625 this->print_on(st); 3626 st->cr(); 3627 3628 #if defined(SUPPORT_ASSEMBLY) 3629 //---------------------------------- 3630 //---< Print real disassembly >--- 3631 //---------------------------------- 3632 if (! use_compressed_format) { 3633 st->print_cr("[Disassembly]"); 3634 Disassembler::decode(const_cast<nmethod*>(this), st); 3635 st->bol(); 3636 st->print_cr("[/Disassembly]"); 3637 return; 3638 } 3639 #endif 3640 3641 #if defined(SUPPORT_ABSTRACT_ASSEMBLY) 3642 3643 // Compressed undisassembled disassembly format. 3644 // The following status values are defined/supported: 3645 // = 0 - currently at bol() position, nothing printed yet on current line. 3646 // = 1 - currently at position after print_location(). 3647 // > 1 - in the midst of printing instruction stream bytes. 3648 int compressed_format_idx = 0; 3649 int code_comment_column = 0; 3650 const int instr_maxlen = Assembler::instr_maxlen(); 3651 const uint tabspacing = 8; 3652 unsigned char* start = this->code_begin(); 3653 unsigned char* p = this->code_begin(); 3654 unsigned char* end = this->code_end(); 3655 unsigned char* pss = p; // start of a code section (used for offsets) 3656 3657 if ((start == nullptr) || (end == nullptr)) { 3658 st->print_cr("PrintAssembly not possible due to uninitialized section pointers"); 3659 return; 3660 } 3661 #endif 3662 3663 #if defined(SUPPORT_ABSTRACT_ASSEMBLY) 3664 //---< plain abstract disassembly, no comments or anything, just section headers >--- 3665 if (use_compressed_format && ! compressed_with_comments) { 3666 const_cast<nmethod*>(this)->print_constant_pool(st); 3667 3668 //---< Open the output (Marker for post-mortem disassembler) >--- 3669 st->print_cr("[MachCode]"); 3670 const char* header = nullptr; 3671 address p0 = p; 3672 while (p < end) { 3673 address pp = p; 3674 while ((p < end) && (header == nullptr)) { 3675 header = nmethod_section_label(p); 3676 pp = p; 3677 p += Assembler::instr_len(p); 3678 } 3679 if (pp > p0) { 3680 AbstractDisassembler::decode_range_abstract(p0, pp, start, end, st, Assembler::instr_maxlen()); 3681 p0 = pp; 3682 p = pp; 3683 header = nullptr; 3684 } else if (header != nullptr) { 3685 st->bol(); 3686 st->print_cr("%s", header); 3687 header = nullptr; 3688 } 3689 } 3690 //---< Close the output (Marker for post-mortem disassembler) >--- 3691 st->bol(); 3692 st->print_cr("[/MachCode]"); 3693 return; 3694 } 3695 #endif 3696 3697 #if defined(SUPPORT_ABSTRACT_ASSEMBLY) 3698 //---< abstract disassembly with comments and section headers merged in >--- 3699 if (compressed_with_comments) { 3700 const_cast<nmethod*>(this)->print_constant_pool(st); 3701 3702 //---< Open the output (Marker for post-mortem disassembler) >--- 3703 st->print_cr("[MachCode]"); 3704 while ((p < end) && (p != nullptr)) { 3705 const int instruction_size_in_bytes = Assembler::instr_len(p); 3706 3707 //---< Block comments for nmethod. Interrupts instruction stream, if any. >--- 3708 // Outputs a bol() before and a cr() after, but only if a comment is printed. 3709 // Prints nmethod_section_label as well. 3710 if (AbstractDisassembler::show_block_comment()) { 3711 print_block_comment(st, p); 3712 if (st->position() == 0) { 3713 compressed_format_idx = 0; 3714 } 3715 } 3716 3717 //---< New location information after line break >--- 3718 if (compressed_format_idx == 0) { 3719 code_comment_column = Disassembler::print_location(p, pss, end, st, false, false); 3720 compressed_format_idx = 1; 3721 } 3722 3723 //---< Code comment for current instruction. Address range [p..(p+len)) >--- 3724 unsigned char* p_end = p + (ssize_t)instruction_size_in_bytes; 3725 S390_ONLY(if (p_end > end) p_end = end;) // avoid getting past the end 3726 3727 if (AbstractDisassembler::show_comment() && const_cast<nmethod*>(this)->has_code_comment(p, p_end)) { 3728 //---< interrupt instruction byte stream for code comment >--- 3729 if (compressed_format_idx > 1) { 3730 st->cr(); // interrupt byte stream 3731 st->cr(); // add an empty line 3732 code_comment_column = Disassembler::print_location(p, pss, end, st, false, false); 3733 } 3734 const_cast<nmethod*>(this)->print_code_comment_on(st, code_comment_column, p, p_end ); 3735 st->bol(); 3736 compressed_format_idx = 0; 3737 } 3738 3739 //---< New location information after line break >--- 3740 if (compressed_format_idx == 0) { 3741 code_comment_column = Disassembler::print_location(p, pss, end, st, false, false); 3742 compressed_format_idx = 1; 3743 } 3744 3745 //---< Nicely align instructions for readability >--- 3746 if (compressed_format_idx > 1) { 3747 Disassembler::print_delimiter(st); 3748 } 3749 3750 //---< Now, finally, print the actual instruction bytes >--- 3751 unsigned char* p0 = p; 3752 p = Disassembler::decode_instruction_abstract(p, st, instruction_size_in_bytes, instr_maxlen); 3753 compressed_format_idx += (int)(p - p0); 3754 3755 if (Disassembler::start_newline(compressed_format_idx-1)) { 3756 st->cr(); 3757 compressed_format_idx = 0; 3758 } 3759 } 3760 //---< Close the output (Marker for post-mortem disassembler) >--- 3761 st->bol(); 3762 st->print_cr("[/MachCode]"); 3763 return; 3764 } 3765 #endif 3766 } 3767 3768 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY) 3769 3770 const char* nmethod::reloc_string_for(u_char* begin, u_char* end) { 3771 RelocIterator iter(this, begin, end); 3772 bool have_one = false; 3773 while (iter.next()) { 3774 have_one = true; 3775 switch (iter.type()) { 3776 case relocInfo::none: { 3777 // Skip it and check next 3778 break; 3779 } 3780 case relocInfo::oop_type: { 3781 // Get a non-resizable resource-allocated stringStream. 3782 // Our callees make use of (nested) ResourceMarks. 3783 stringStream st(NEW_RESOURCE_ARRAY(char, 1024), 1024); 3784 oop_Relocation* r = iter.oop_reloc(); 3785 oop obj = r->oop_value(); 3786 st.print("oop("); 3787 if (obj == nullptr) st.print("nullptr"); 3788 else obj->print_value_on(&st); 3789 st.print(")"); 3790 return st.as_string(); 3791 } 3792 case relocInfo::metadata_type: { 3793 stringStream st; 3794 metadata_Relocation* r = iter.metadata_reloc(); 3795 Metadata* obj = r->metadata_value(); 3796 st.print("metadata("); 3797 if (obj == nullptr) st.print("nullptr"); 3798 else obj->print_value_on(&st); 3799 st.print(")"); 3800 return st.as_string(); 3801 } 3802 case relocInfo::runtime_call_type: 3803 case relocInfo::runtime_call_w_cp_type: { 3804 stringStream st; 3805 st.print("runtime_call"); 3806 CallRelocation* r = (CallRelocation*)iter.reloc(); 3807 address dest = r->destination(); 3808 if (StubRoutines::contains(dest)) { 3809 StubCodeDesc* desc = StubCodeDesc::desc_for(dest); 3810 if (desc == nullptr) { 3811 desc = StubCodeDesc::desc_for(dest + frame::pc_return_offset); 3812 } 3813 if (desc != nullptr) { 3814 st.print(" Stub::%s", desc->name()); 3815 return st.as_string(); 3816 } 3817 } 3818 CodeBlob* cb = CodeCache::find_blob(dest); 3819 if (cb != nullptr) { 3820 st.print(" %s", cb->name()); 3821 } else { 3822 ResourceMark rm; 3823 const int buflen = 1024; 3824 char* buf = NEW_RESOURCE_ARRAY(char, buflen); 3825 int offset; 3826 if (os::dll_address_to_function_name(dest, buf, buflen, &offset)) { 3827 st.print(" %s", buf); 3828 if (offset != 0) { 3829 st.print("+%d", offset); 3830 } 3831 } 3832 } 3833 return st.as_string(); 3834 } 3835 case relocInfo::virtual_call_type: { 3836 stringStream st; 3837 st.print_raw("virtual_call"); 3838 virtual_call_Relocation* r = iter.virtual_call_reloc(); 3839 Method* m = r->method_value(); 3840 if (m != nullptr) { 3841 assert(m->is_method(), ""); 3842 m->print_short_name(&st); 3843 } 3844 return st.as_string(); 3845 } 3846 case relocInfo::opt_virtual_call_type: { 3847 stringStream st; 3848 st.print_raw("optimized virtual_call"); 3849 opt_virtual_call_Relocation* r = iter.opt_virtual_call_reloc(); 3850 Method* m = r->method_value(); 3851 if (m != nullptr) { 3852 assert(m->is_method(), ""); 3853 m->print_short_name(&st); 3854 } 3855 return st.as_string(); 3856 } 3857 case relocInfo::static_call_type: { 3858 stringStream st; 3859 st.print_raw("static_call"); 3860 static_call_Relocation* r = iter.static_call_reloc(); 3861 Method* m = r->method_value(); 3862 if (m != nullptr) { 3863 assert(m->is_method(), ""); 3864 m->print_short_name(&st); 3865 } 3866 return st.as_string(); 3867 } 3868 case relocInfo::static_stub_type: return "static_stub"; 3869 case relocInfo::external_word_type: return "external_word"; 3870 case relocInfo::internal_word_type: return "internal_word"; 3871 case relocInfo::section_word_type: return "section_word"; 3872 case relocInfo::poll_type: return "poll"; 3873 case relocInfo::poll_return_type: return "poll_return"; 3874 case relocInfo::trampoline_stub_type: return "trampoline_stub"; 3875 case relocInfo::entry_guard_type: return "entry_guard"; 3876 case relocInfo::post_call_nop_type: return "post_call_nop"; 3877 case relocInfo::barrier_type: { 3878 barrier_Relocation* const reloc = iter.barrier_reloc(); 3879 stringStream st; 3880 st.print("barrier format=%d", reloc->format()); 3881 return st.as_string(); 3882 } 3883 3884 case relocInfo::type_mask: return "type_bit_mask"; 3885 3886 default: { 3887 stringStream st; 3888 st.print("unknown relocInfo=%d", (int) iter.type()); 3889 return st.as_string(); 3890 } 3891 } 3892 } 3893 return have_one ? "other" : nullptr; 3894 } 3895 3896 // Return the last scope in (begin..end] 3897 ScopeDesc* nmethod::scope_desc_in(address begin, address end) { 3898 PcDesc* p = pc_desc_near(begin+1); 3899 if (p != nullptr && p->real_pc(this) <= end) { 3900 return new ScopeDesc(this, p); 3901 } 3902 return nullptr; 3903 } 3904 3905 const char* nmethod::nmethod_section_label(address pos) const { 3906 const char* label = nullptr; 3907 if (pos == code_begin()) label = "[Instructions begin]"; 3908 if (pos == entry_point()) label = "[Entry Point]"; 3909 if (pos == verified_entry_point()) label = "[Verified Entry Point]"; 3910 if (has_method_handle_invokes() && (pos == deopt_mh_handler_begin())) label = "[Deopt MH Handler Code]"; 3911 if (pos == consts_begin() && pos != insts_begin()) label = "[Constants]"; 3912 // Check stub_code before checking exception_handler or deopt_handler. 3913 if (pos == this->stub_begin()) label = "[Stub Code]"; 3914 if (JVMCI_ONLY(_exception_offset >= 0 &&) pos == exception_begin()) label = "[Exception Handler]"; 3915 if (JVMCI_ONLY(_deopt_handler_offset != -1 &&) pos == deopt_handler_begin()) label = "[Deopt Handler Code]"; 3916 return label; 3917 } 3918 3919 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin, bool print_section_labels) const { 3920 if (print_section_labels) { 3921 const char* label = nmethod_section_label(block_begin); 3922 if (label != nullptr) { 3923 stream->bol(); 3924 stream->print_cr("%s", label); 3925 } 3926 } 3927 3928 if (block_begin == entry_point()) { 3929 Method* m = method(); 3930 if (m != nullptr) { 3931 stream->print(" # "); 3932 m->print_value_on(stream); 3933 stream->cr(); 3934 } 3935 if (m != nullptr && !is_osr_method()) { 3936 ResourceMark rm; 3937 int sizeargs = m->size_of_parameters(); 3938 BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs); 3939 VMRegPair* regs = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs); 3940 { 3941 int sig_index = 0; 3942 if (!m->is_static()) 3943 sig_bt[sig_index++] = T_OBJECT; // 'this' 3944 for (SignatureStream ss(m->signature()); !ss.at_return_type(); ss.next()) { 3945 BasicType t = ss.type(); 3946 sig_bt[sig_index++] = t; 3947 if (type2size[t] == 2) { 3948 sig_bt[sig_index++] = T_VOID; 3949 } else { 3950 assert(type2size[t] == 1, "size is 1 or 2"); 3951 } 3952 } 3953 assert(sig_index == sizeargs, ""); 3954 } 3955 const char* spname = "sp"; // make arch-specific? 3956 SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs); 3957 int stack_slot_offset = this->frame_size() * wordSize; 3958 int tab1 = 14, tab2 = 24; 3959 int sig_index = 0; 3960 int arg_index = (m->is_static() ? 0 : -1); 3961 bool did_old_sp = false; 3962 for (SignatureStream ss(m->signature()); !ss.at_return_type(); ) { 3963 bool at_this = (arg_index == -1); 3964 bool at_old_sp = false; 3965 BasicType t = (at_this ? T_OBJECT : ss.type()); 3966 assert(t == sig_bt[sig_index], "sigs in sync"); 3967 if (at_this) 3968 stream->print(" # this: "); 3969 else 3970 stream->print(" # parm%d: ", arg_index); 3971 stream->move_to(tab1); 3972 VMReg fst = regs[sig_index].first(); 3973 VMReg snd = regs[sig_index].second(); 3974 if (fst->is_reg()) { 3975 stream->print("%s", fst->name()); 3976 if (snd->is_valid()) { 3977 stream->print(":%s", snd->name()); 3978 } 3979 } else if (fst->is_stack()) { 3980 int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset; 3981 if (offset == stack_slot_offset) at_old_sp = true; 3982 stream->print("[%s+0x%x]", spname, offset); 3983 } else { 3984 stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd); 3985 } 3986 stream->print(" "); 3987 stream->move_to(tab2); 3988 stream->print("= "); 3989 if (at_this) { 3990 m->method_holder()->print_value_on(stream); 3991 } else { 3992 bool did_name = false; 3993 if (!at_this && ss.is_reference()) { 3994 Symbol* name = ss.as_symbol(); 3995 name->print_value_on(stream); 3996 did_name = true; 3997 } 3998 if (!did_name) 3999 stream->print("%s", type2name(t)); 4000 } 4001 if (at_old_sp) { 4002 stream->print(" (%s of caller)", spname); 4003 did_old_sp = true; 4004 } 4005 stream->cr(); 4006 sig_index += type2size[t]; 4007 arg_index += 1; 4008 if (!at_this) ss.next(); 4009 } 4010 if (!did_old_sp) { 4011 stream->print(" # "); 4012 stream->move_to(tab1); 4013 stream->print("[%s+0x%x]", spname, stack_slot_offset); 4014 stream->print(" (%s of caller)", spname); 4015 stream->cr(); 4016 } 4017 } 4018 } 4019 } 4020 4021 // Returns whether this nmethod has code comments. 4022 bool nmethod::has_code_comment(address begin, address end) { 4023 // scopes? 4024 ScopeDesc* sd = scope_desc_in(begin, end); 4025 if (sd != nullptr) return true; 4026 4027 // relocations? 4028 const char* str = reloc_string_for(begin, end); 4029 if (str != nullptr) return true; 4030 4031 // implicit exceptions? 4032 int cont_offset = ImplicitExceptionTable(this).continuation_offset((uint)(begin - code_begin())); 4033 if (cont_offset != 0) return true; 4034 4035 return false; 4036 } 4037 4038 void nmethod::print_code_comment_on(outputStream* st, int column, address begin, address end) { 4039 ImplicitExceptionTable implicit_table(this); 4040 int pc_offset = (int)(begin - code_begin()); 4041 int cont_offset = implicit_table.continuation_offset(pc_offset); 4042 bool oop_map_required = false; 4043 if (cont_offset != 0) { 4044 st->move_to(column, 6, 0); 4045 if (pc_offset == cont_offset) { 4046 st->print("; implicit exception: deoptimizes"); 4047 oop_map_required = true; 4048 } else { 4049 st->print("; implicit exception: dispatches to " INTPTR_FORMAT, p2i(code_begin() + cont_offset)); 4050 } 4051 } 4052 4053 // Find an oopmap in (begin, end]. We use the odd half-closed 4054 // interval so that oop maps and scope descs which are tied to the 4055 // byte after a call are printed with the call itself. OopMaps 4056 // associated with implicit exceptions are printed with the implicit 4057 // instruction. 4058 address base = code_begin(); 4059 ImmutableOopMapSet* oms = oop_maps(); 4060 if (oms != nullptr) { 4061 for (int i = 0, imax = oms->count(); i < imax; i++) { 4062 const ImmutableOopMapPair* pair = oms->pair_at(i); 4063 const ImmutableOopMap* om = pair->get_from(oms); 4064 address pc = base + pair->pc_offset(); 4065 if (pc >= begin) { 4066 #if INCLUDE_JVMCI 4067 bool is_implicit_deopt = implicit_table.continuation_offset(pair->pc_offset()) == (uint) pair->pc_offset(); 4068 #else 4069 bool is_implicit_deopt = false; 4070 #endif 4071 if (is_implicit_deopt ? pc == begin : pc > begin && pc <= end) { 4072 st->move_to(column, 6, 0); 4073 st->print("; "); 4074 om->print_on(st); 4075 oop_map_required = false; 4076 } 4077 } 4078 if (pc > end) { 4079 break; 4080 } 4081 } 4082 } 4083 assert(!oop_map_required, "missed oopmap"); 4084 4085 Thread* thread = Thread::current(); 4086 4087 // Print any debug info present at this pc. 4088 ScopeDesc* sd = scope_desc_in(begin, end); 4089 if (sd != nullptr) { 4090 st->move_to(column, 6, 0); 4091 if (sd->bci() == SynchronizationEntryBCI) { 4092 st->print(";*synchronization entry"); 4093 } else if (sd->bci() == AfterBci) { 4094 st->print(";* method exit (unlocked if synchronized)"); 4095 } else if (sd->bci() == UnwindBci) { 4096 st->print(";* unwind (locked if synchronized)"); 4097 } else if (sd->bci() == AfterExceptionBci) { 4098 st->print(";* unwind (unlocked if synchronized)"); 4099 } else if (sd->bci() == UnknownBci) { 4100 st->print(";* unknown"); 4101 } else if (sd->bci() == InvalidFrameStateBci) { 4102 st->print(";* invalid frame state"); 4103 } else { 4104 if (sd->method() == nullptr) { 4105 st->print("method is nullptr"); 4106 } else if (sd->method()->is_native()) { 4107 st->print("method is native"); 4108 } else { 4109 Bytecodes::Code bc = sd->method()->java_code_at(sd->bci()); 4110 st->print(";*%s", Bytecodes::name(bc)); 4111 switch (bc) { 4112 case Bytecodes::_invokevirtual: 4113 case Bytecodes::_invokespecial: 4114 case Bytecodes::_invokestatic: 4115 case Bytecodes::_invokeinterface: 4116 { 4117 Bytecode_invoke invoke(methodHandle(thread, sd->method()), sd->bci()); 4118 st->print(" "); 4119 if (invoke.name() != nullptr) 4120 invoke.name()->print_symbol_on(st); 4121 else 4122 st->print("<UNKNOWN>"); 4123 break; 4124 } 4125 case Bytecodes::_getfield: 4126 case Bytecodes::_putfield: 4127 case Bytecodes::_getstatic: 4128 case Bytecodes::_putstatic: 4129 { 4130 Bytecode_field field(methodHandle(thread, sd->method()), sd->bci()); 4131 st->print(" "); 4132 if (field.name() != nullptr) 4133 field.name()->print_symbol_on(st); 4134 else 4135 st->print("<UNKNOWN>"); 4136 } 4137 default: 4138 break; 4139 } 4140 } 4141 st->print(" {reexecute=%d rethrow=%d return_oop=%d}", sd->should_reexecute(), sd->rethrow_exception(), sd->return_oop()); 4142 } 4143 4144 // Print all scopes 4145 for (;sd != nullptr; sd = sd->sender()) { 4146 st->move_to(column, 6, 0); 4147 st->print("; -"); 4148 if (sd->should_reexecute()) { 4149 st->print(" (reexecute)"); 4150 } 4151 if (sd->method() == nullptr) { 4152 st->print("method is nullptr"); 4153 } else { 4154 sd->method()->print_short_name(st); 4155 } 4156 int lineno = sd->method()->line_number_from_bci(sd->bci()); 4157 if (lineno != -1) { 4158 st->print("@%d (line %d)", sd->bci(), lineno); 4159 } else { 4160 st->print("@%d", sd->bci()); 4161 } 4162 st->cr(); 4163 } 4164 } 4165 4166 // Print relocation information 4167 // Prevent memory leak: allocating without ResourceMark. 4168 ResourceMark rm; 4169 const char* str = reloc_string_for(begin, end); 4170 if (str != nullptr) { 4171 if (sd != nullptr) st->cr(); 4172 st->move_to(column, 6, 0); 4173 st->print("; {%s}", str); 4174 } 4175 } 4176 4177 #endif 4178 4179 address nmethod::call_instruction_address(address pc) const { 4180 if (NativeCall::is_call_before(pc)) { 4181 NativeCall *ncall = nativeCall_before(pc); 4182 return ncall->instruction_address(); 4183 } 4184 return nullptr; 4185 } 4186 4187 void nmethod::print_value_on_impl(outputStream* st) const { 4188 st->print_cr("nmethod"); 4189 #if defined(SUPPORT_DATA_STRUCTS) 4190 print_on_with_msg(st, nullptr); 4191 #endif 4192 } 4193 4194 #ifndef PRODUCT 4195 4196 void nmethod::print_calls(outputStream* st) { 4197 RelocIterator iter(this); 4198 while (iter.next()) { 4199 switch (iter.type()) { 4200 case relocInfo::virtual_call_type: { 4201 CompiledICLocker ml_verify(this); 4202 CompiledIC_at(&iter)->print(); 4203 break; 4204 } 4205 case relocInfo::static_call_type: 4206 case relocInfo::opt_virtual_call_type: 4207 st->print_cr("Direct call at " INTPTR_FORMAT, p2i(iter.reloc()->addr())); 4208 CompiledDirectCall::at(iter.reloc())->print(); 4209 break; 4210 default: 4211 break; 4212 } 4213 } 4214 } 4215 4216 void nmethod::print_statistics() { 4217 ttyLocker ttyl; 4218 if (xtty != nullptr) xtty->head("statistics type='nmethod'"); 4219 native_nmethod_stats.print_native_nmethod_stats(); 4220 #ifdef COMPILER1 4221 c1_java_nmethod_stats.print_nmethod_stats("C1"); 4222 #endif 4223 #ifdef COMPILER2 4224 c2_java_nmethod_stats.print_nmethod_stats("C2"); 4225 #endif 4226 #if INCLUDE_JVMCI 4227 jvmci_java_nmethod_stats.print_nmethod_stats("JVMCI"); 4228 #endif 4229 unknown_java_nmethod_stats.print_nmethod_stats("Unknown"); 4230 DebugInformationRecorder::print_statistics(); 4231 pc_nmethod_stats.print_pc_stats(); 4232 Dependencies::print_statistics(); 4233 ExternalsRecorder::print_statistics(); 4234 if (xtty != nullptr) xtty->tail("statistics"); 4235 } 4236 4237 #endif // !PRODUCT 4238 4239 #if INCLUDE_JVMCI 4240 void nmethod::update_speculation(JavaThread* thread) { 4241 jlong speculation = thread->pending_failed_speculation(); 4242 if (speculation != 0) { 4243 guarantee(jvmci_nmethod_data() != nullptr, "failed speculation in nmethod without failed speculation list"); 4244 jvmci_nmethod_data()->add_failed_speculation(this, speculation); 4245 thread->set_pending_failed_speculation(0); 4246 } 4247 } 4248 4249 const char* nmethod::jvmci_name() { 4250 if (jvmci_nmethod_data() != nullptr) { 4251 return jvmci_nmethod_data()->name(); 4252 } 4253 return nullptr; 4254 } 4255 #endif 4256 4257 void nmethod::prepare_for_archiving_impl() { 4258 CodeBlob::prepare_for_archiving_impl(); 4259 _deoptimization_generation = 0; 4260 _gc_epoch = 0; 4261 _method_profiling_count = 0; 4262 _osr_link = nullptr; 4263 _method = nullptr; 4264 _immutable_data = nullptr; 4265 _pc_desc_container = nullptr; 4266 _exception_cache = nullptr; 4267 _gc_data = nullptr; 4268 _oops_do_mark_link = nullptr; 4269 _compiled_ic_data = nullptr; 4270 _osr_entry_point = nullptr; 4271 _compile_id = -1; 4272 _deoptimization_status = not_marked; 4273 _is_unloading_state = 0; 4274 _state = not_installed; 4275 }