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