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