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