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