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/compiledMethod.inline.hpp" 30 #include "code/dependencies.hpp" 31 #include "code/nativeInst.hpp" 32 #include "code/nmethod.hpp" 33 #include "code/scopeDesc.hpp" 34 #include "compiler/abstractCompiler.hpp" 35 #include "compiler/compilationLog.hpp" 36 #include "compiler/compileBroker.hpp" 37 #include "compiler/compileLog.hpp" 38 #include "compiler/compileTask.hpp" 39 #include "compiler/compilerDirectives.hpp" 40 #include "compiler/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.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 //--------------------------------------------------------------------------------- 114 // NMethod statistics 115 // They are printed under various flags, including: 116 // PrintC1Statistics, PrintOptoStatistics, LogVMOutput, and LogCompilation. 117 // (In the latter two cases, they like other stats are printed to the log only.) 118 119 #ifndef PRODUCT 120 // These variables are put into one block to reduce relocations 121 // and make it simpler to print from the debugger. 122 struct java_nmethod_stats_struct { 123 uint nmethod_count; 124 uint total_size; 125 uint relocation_size; 126 uint consts_size; 127 uint insts_size; 128 uint stub_size; 129 uint scopes_data_size; 130 uint scopes_pcs_size; 131 uint dependencies_size; 132 uint handler_table_size; 133 uint nul_chk_table_size; 134 #if INCLUDE_JVMCI 135 uint speculations_size; 136 uint jvmci_data_size; 137 #endif 138 uint oops_size; 139 uint metadata_size; 140 141 void note_nmethod(nmethod* nm) { 142 nmethod_count += 1; 143 total_size += nm->size(); 144 relocation_size += nm->relocation_size(); 145 consts_size += nm->consts_size(); 146 insts_size += nm->insts_size(); 147 stub_size += nm->stub_size(); 148 oops_size += nm->oops_size(); 149 metadata_size += nm->metadata_size(); 150 scopes_data_size += nm->scopes_data_size(); 151 scopes_pcs_size += nm->scopes_pcs_size(); 152 dependencies_size += nm->dependencies_size(); 153 handler_table_size += nm->handler_table_size(); 154 nul_chk_table_size += nm->nul_chk_table_size(); 155 #if INCLUDE_JVMCI 156 speculations_size += nm->speculations_size(); 157 jvmci_data_size += nm->jvmci_data_size(); 158 #endif 159 } 160 void print_nmethod_stats(const char* name) { 161 if (nmethod_count == 0) return; 162 tty->print_cr("Statistics for %u bytecoded nmethods for %s:", nmethod_count, name); 163 if (total_size != 0) tty->print_cr(" total in heap = %u", total_size); 164 if (nmethod_count != 0) tty->print_cr(" header = " SIZE_FORMAT, nmethod_count * sizeof(nmethod)); 165 if (relocation_size != 0) tty->print_cr(" relocation = %u", relocation_size); 166 if (consts_size != 0) tty->print_cr(" constants = %u", consts_size); 167 if (insts_size != 0) tty->print_cr(" main code = %u", insts_size); 168 if (stub_size != 0) tty->print_cr(" stub code = %u", stub_size); 169 if (oops_size != 0) tty->print_cr(" oops = %u", oops_size); 170 if (metadata_size != 0) tty->print_cr(" metadata = %u", metadata_size); 171 if (scopes_data_size != 0) tty->print_cr(" scopes data = %u", scopes_data_size); 172 if (scopes_pcs_size != 0) tty->print_cr(" scopes pcs = %u", scopes_pcs_size); 173 if (dependencies_size != 0) tty->print_cr(" dependencies = %u", dependencies_size); 174 if (handler_table_size != 0) tty->print_cr(" handler table = %u", handler_table_size); 175 if (nul_chk_table_size != 0) tty->print_cr(" nul chk table = %u", nul_chk_table_size); 176 #if INCLUDE_JVMCI 177 if (speculations_size != 0) tty->print_cr(" speculations = %u", speculations_size); 178 if (jvmci_data_size != 0) tty->print_cr(" JVMCI data = %u", jvmci_data_size); 179 #endif 180 } 181 }; 182 183 struct native_nmethod_stats_struct { 184 uint native_nmethod_count; 185 uint native_total_size; 186 uint native_relocation_size; 187 uint native_insts_size; 188 uint native_oops_size; 189 uint native_metadata_size; 190 void note_native_nmethod(nmethod* nm) { 191 native_nmethod_count += 1; 192 native_total_size += nm->size(); 193 native_relocation_size += nm->relocation_size(); 194 native_insts_size += nm->insts_size(); 195 native_oops_size += nm->oops_size(); 196 native_metadata_size += nm->metadata_size(); 197 } 198 void print_native_nmethod_stats() { 199 if (native_nmethod_count == 0) return; 200 tty->print_cr("Statistics for %u native nmethods:", native_nmethod_count); 201 if (native_total_size != 0) tty->print_cr(" N. total size = %u", native_total_size); 202 if (native_relocation_size != 0) tty->print_cr(" N. relocation = %u", native_relocation_size); 203 if (native_insts_size != 0) tty->print_cr(" N. main code = %u", native_insts_size); 204 if (native_oops_size != 0) tty->print_cr(" N. oops = %u", native_oops_size); 205 if (native_metadata_size != 0) tty->print_cr(" N. metadata = %u", native_metadata_size); 206 } 207 }; 208 209 struct pc_nmethod_stats_struct { 210 uint pc_desc_resets; // number of resets (= number of caches) 211 uint pc_desc_queries; // queries to nmethod::find_pc_desc 212 uint pc_desc_approx; // number of those which have approximate true 213 uint pc_desc_repeats; // number of _pc_descs[0] hits 214 uint pc_desc_hits; // number of LRU cache hits 215 uint pc_desc_tests; // total number of PcDesc examinations 216 uint pc_desc_searches; // total number of quasi-binary search steps 217 uint pc_desc_adds; // number of LUR cache insertions 218 219 void print_pc_stats() { 220 tty->print_cr("PcDesc Statistics: %u queries, %.2f comparisons per query", 221 pc_desc_queries, 222 (double)(pc_desc_tests + pc_desc_searches) 223 / pc_desc_queries); 224 tty->print_cr(" caches=%d queries=%u/%u, hits=%u+%u, tests=%u+%u, adds=%u", 225 pc_desc_resets, 226 pc_desc_queries, pc_desc_approx, 227 pc_desc_repeats, pc_desc_hits, 228 pc_desc_tests, pc_desc_searches, pc_desc_adds); 229 } 230 }; 231 232 #ifdef COMPILER1 233 static java_nmethod_stats_struct c1_java_nmethod_stats; 234 #endif 235 #ifdef COMPILER2 236 static java_nmethod_stats_struct c2_java_nmethod_stats; 237 #endif 238 #if INCLUDE_JVMCI 239 static java_nmethod_stats_struct jvmci_java_nmethod_stats; 240 #endif 241 static java_nmethod_stats_struct unknown_java_nmethod_stats; 242 243 static native_nmethod_stats_struct native_nmethod_stats; 244 static pc_nmethod_stats_struct pc_nmethod_stats; 245 246 static void note_java_nmethod(nmethod* nm) { 247 #ifdef COMPILER1 248 if (nm->is_compiled_by_c1()) { 249 c1_java_nmethod_stats.note_nmethod(nm); 250 } else 251 #endif 252 #ifdef COMPILER2 253 if (nm->is_compiled_by_c2()) { 254 c2_java_nmethod_stats.note_nmethod(nm); 255 } else 256 #endif 257 #if INCLUDE_JVMCI 258 if (nm->is_compiled_by_jvmci()) { 259 jvmci_java_nmethod_stats.note_nmethod(nm); 260 } else 261 #endif 262 { 263 unknown_java_nmethod_stats.note_nmethod(nm); 264 } 265 } 266 #endif // !PRODUCT 267 268 //--------------------------------------------------------------------------------- 269 270 271 ExceptionCache::ExceptionCache(Handle exception, address pc, address handler) { 272 assert(pc != nullptr, "Must be non null"); 273 assert(exception.not_null(), "Must be non null"); 274 assert(handler != nullptr, "Must be non null"); 275 276 _count = 0; 277 _exception_type = exception->klass(); 278 _next = nullptr; 279 _purge_list_next = nullptr; 280 281 add_address_and_handler(pc,handler); 282 } 283 284 285 address ExceptionCache::match(Handle exception, address pc) { 286 assert(pc != nullptr,"Must be non null"); 287 assert(exception.not_null(),"Must be non null"); 288 if (exception->klass() == exception_type()) { 289 return (test_address(pc)); 290 } 291 292 return nullptr; 293 } 294 295 296 bool ExceptionCache::match_exception_with_space(Handle exception) { 297 assert(exception.not_null(),"Must be non null"); 298 if (exception->klass() == exception_type() && count() < cache_size) { 299 return true; 300 } 301 return false; 302 } 303 304 305 address ExceptionCache::test_address(address addr) { 306 int limit = count(); 307 for (int i = 0; i < limit; i++) { 308 if (pc_at(i) == addr) { 309 return handler_at(i); 310 } 311 } 312 return nullptr; 313 } 314 315 316 bool ExceptionCache::add_address_and_handler(address addr, address handler) { 317 if (test_address(addr) == handler) return true; 318 319 int index = count(); 320 if (index < cache_size) { 321 set_pc_at(index, addr); 322 set_handler_at(index, handler); 323 increment_count(); 324 return true; 325 } 326 return false; 327 } 328 329 ExceptionCache* ExceptionCache::next() { 330 return Atomic::load(&_next); 331 } 332 333 void ExceptionCache::set_next(ExceptionCache *ec) { 334 Atomic::store(&_next, ec); 335 } 336 337 //----------------------------------------------------------------------------- 338 339 340 // Helper used by both find_pc_desc methods. 341 static inline bool match_desc(PcDesc* pc, int pc_offset, bool approximate) { 342 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_tests); 343 if (!approximate) 344 return pc->pc_offset() == pc_offset; 345 else 346 return (pc-1)->pc_offset() < pc_offset && pc_offset <= pc->pc_offset(); 347 } 348 349 void PcDescCache::reset_to(PcDesc* initial_pc_desc) { 350 if (initial_pc_desc == nullptr) { 351 _pc_descs[0] = nullptr; // native method; no PcDescs at all 352 return; 353 } 354 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_resets); 355 // reset the cache by filling it with benign (non-null) values 356 assert(initial_pc_desc->pc_offset() < 0, "must be sentinel"); 357 for (int i = 0; i < cache_size; i++) 358 _pc_descs[i] = initial_pc_desc; 359 } 360 361 PcDesc* PcDescCache::find_pc_desc(int pc_offset, bool approximate) { 362 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_queries); 363 NOT_PRODUCT(if (approximate) ++pc_nmethod_stats.pc_desc_approx); 364 365 // Note: one might think that caching the most recently 366 // read value separately would be a win, but one would be 367 // wrong. When many threads are updating it, the cache 368 // line it's in would bounce between caches, negating 369 // any benefit. 370 371 // In order to prevent race conditions do not load cache elements 372 // repeatedly, but use a local copy: 373 PcDesc* res; 374 375 // Step one: Check the most recently added value. 376 res = _pc_descs[0]; 377 if (res == nullptr) return nullptr; // native method; no PcDescs at all 378 if (match_desc(res, pc_offset, approximate)) { 379 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_repeats); 380 return res; 381 } 382 383 // Step two: Check the rest of the LRU cache. 384 for (int i = 1; i < cache_size; ++i) { 385 res = _pc_descs[i]; 386 if (res->pc_offset() < 0) break; // optimization: skip empty cache 387 if (match_desc(res, pc_offset, approximate)) { 388 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_hits); 389 return res; 390 } 391 } 392 393 // Report failure. 394 return nullptr; 395 } 396 397 void PcDescCache::add_pc_desc(PcDesc* pc_desc) { 398 MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, Thread::current());) 399 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_adds); 400 // Update the LRU cache by shifting pc_desc forward. 401 for (int i = 0; i < cache_size; i++) { 402 PcDesc* next = _pc_descs[i]; 403 _pc_descs[i] = pc_desc; 404 pc_desc = next; 405 } 406 } 407 408 // adjust pcs_size so that it is a multiple of both oopSize and 409 // sizeof(PcDesc) (assumes that if sizeof(PcDesc) is not a multiple 410 // of oopSize, then 2*sizeof(PcDesc) is) 411 static int adjust_pcs_size(int pcs_size) { 412 int nsize = align_up(pcs_size, oopSize); 413 if ((nsize % sizeof(PcDesc)) != 0) { 414 nsize = pcs_size + sizeof(PcDesc); 415 } 416 assert((nsize % oopSize) == 0, "correct alignment"); 417 return nsize; 418 } 419 420 421 int nmethod::total_size() const { 422 return 423 consts_size() + 424 insts_size() + 425 stub_size() + 426 scopes_data_size() + 427 scopes_pcs_size() + 428 handler_table_size() + 429 nul_chk_table_size(); 430 } 431 432 const char* nmethod::compile_kind() const { 433 if (is_osr_method()) return "osr"; 434 if (method() != nullptr && is_native_method()) { 435 if (method()->is_continuation_native_intrinsic()) { 436 return "cnt"; 437 } 438 return "c2n"; 439 } 440 return nullptr; 441 } 442 443 // Fill in default values for various flag fields 444 void nmethod::init_defaults() { 445 _state = not_installed; 446 _has_flushed_dependencies = 0; 447 _load_reported = false; // jvmti state 448 449 _oops_do_mark_link = nullptr; 450 _osr_link = nullptr; 451 #if INCLUDE_RTM_OPT 452 _rtm_state = NoRTM; 453 #endif 454 } 455 456 #ifdef ASSERT 457 class CheckForOopsClosure : public OopClosure { 458 bool _found_oop = false; 459 public: 460 virtual void do_oop(oop* o) { _found_oop = true; } 461 virtual void do_oop(narrowOop* o) { _found_oop = true; } 462 bool found_oop() { return _found_oop; } 463 }; 464 class CheckForMetadataClosure : public MetadataClosure { 465 bool _found_metadata = false; 466 Metadata* _ignore = nullptr; 467 public: 468 CheckForMetadataClosure(Metadata* ignore) : _ignore(ignore) {} 469 virtual void do_metadata(Metadata* md) { if (md != _ignore) _found_metadata = true; } 470 bool found_metadata() { return _found_metadata; } 471 }; 472 473 static void assert_no_oops_or_metadata(nmethod* nm) { 474 if (nm == nullptr) return; 475 assert(nm->oop_maps() == nullptr, "expectation"); 476 477 CheckForOopsClosure cfo; 478 nm->oops_do(&cfo); 479 assert(!cfo.found_oop(), "no oops allowed"); 480 481 // We allow an exception for the own Method, but require its class to be permanent. 482 Method* own_method = nm->method(); 483 CheckForMetadataClosure cfm(/* ignore reference to own Method */ own_method); 484 nm->metadata_do(&cfm); 485 assert(!cfm.found_metadata(), "no metadata allowed"); 486 487 assert(own_method->method_holder()->class_loader_data()->is_permanent_class_loader_data(), 488 "Method's class needs to be permanent"); 489 } 490 #endif 491 492 nmethod* nmethod::new_native_nmethod(const methodHandle& method, 493 int compile_id, 494 CodeBuffer *code_buffer, 495 int vep_offset, 496 int frame_complete, 497 int frame_size, 498 ByteSize basic_lock_owner_sp_offset, 499 ByteSize basic_lock_sp_offset, 500 OopMapSet* oop_maps, 501 int exception_handler) { 502 code_buffer->finalize_oop_references(method); 503 // create nmethod 504 nmethod* nm = nullptr; 505 int native_nmethod_size = CodeBlob::allocation_size(code_buffer, sizeof(nmethod)); 506 { 507 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 508 509 CodeOffsets offsets; 510 offsets.set_value(CodeOffsets::Verified_Entry, vep_offset); 511 offsets.set_value(CodeOffsets::Frame_Complete, frame_complete); 512 if (exception_handler != -1) { 513 offsets.set_value(CodeOffsets::Exceptions, exception_handler); 514 } 515 516 // MH intrinsics are dispatch stubs which are compatible with NonNMethod space. 517 // IsUnloadingBehaviour::is_unloading needs to handle them separately. 518 bool allow_NonNMethod_space = method->can_be_allocated_in_NonNMethod_space(); 519 nm = new (native_nmethod_size, allow_NonNMethod_space) 520 nmethod(method(), compiler_none, native_nmethod_size, 521 compile_id, &offsets, 522 code_buffer, frame_size, 523 basic_lock_owner_sp_offset, 524 basic_lock_sp_offset, 525 oop_maps); 526 DEBUG_ONLY( if (allow_NonNMethod_space) assert_no_oops_or_metadata(nm); ) 527 NOT_PRODUCT(if (nm != nullptr) native_nmethod_stats.note_native_nmethod(nm)); 528 } 529 530 if (nm != nullptr) { 531 // verify nmethod 532 debug_only(nm->verify();) // might block 533 534 nm->log_new_nmethod(); 535 } 536 return nm; 537 } 538 539 nmethod* nmethod::new_nmethod(const methodHandle& method, 540 int compile_id, 541 int entry_bci, 542 CodeOffsets* offsets, 543 int orig_pc_offset, 544 DebugInformationRecorder* debug_info, 545 Dependencies* dependencies, 546 CodeBuffer* code_buffer, int frame_size, 547 OopMapSet* oop_maps, 548 ExceptionHandlerTable* handler_table, 549 ImplicitExceptionTable* nul_chk_table, 550 AbstractCompiler* compiler, 551 CompLevel comp_level 552 #if INCLUDE_JVMCI 553 , char* speculations, 554 int speculations_len, 555 JVMCINMethodData* jvmci_data 556 #endif 557 ) 558 { 559 assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR"); 560 code_buffer->finalize_oop_references(method); 561 // create nmethod 562 nmethod* nm = nullptr; 563 #if INCLUDE_JVMCI 564 int jvmci_data_size = compiler->is_jvmci() ? jvmci_data->size() : 0; 565 #endif 566 int nmethod_size = 567 CodeBlob::allocation_size(code_buffer, sizeof(nmethod)) 568 + adjust_pcs_size(debug_info->pcs_size()) 569 + align_up((int)dependencies->size_in_bytes(), oopSize) 570 + align_up(handler_table->size_in_bytes() , oopSize) 571 + align_up(nul_chk_table->size_in_bytes() , oopSize) 572 #if INCLUDE_JVMCI 573 + align_up(speculations_len , oopSize) 574 + align_up(jvmci_data_size , oopSize) 575 #endif 576 + align_up(debug_info->data_size() , oopSize); 577 { 578 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 579 580 nm = new (nmethod_size, comp_level) 581 nmethod(method(), compiler->type(), nmethod_size, compile_id, entry_bci, offsets, 582 orig_pc_offset, debug_info, dependencies, code_buffer, frame_size, 583 oop_maps, 584 handler_table, 585 nul_chk_table, 586 compiler, 587 comp_level 588 #if INCLUDE_JVMCI 589 , speculations, 590 speculations_len, 591 jvmci_data 592 #endif 593 ); 594 595 if (nm != nullptr) { 596 // To make dependency checking during class loading fast, record 597 // the nmethod dependencies in the classes it is dependent on. 598 // This allows the dependency checking code to simply walk the 599 // class hierarchy above the loaded class, checking only nmethods 600 // which are dependent on those classes. The slow way is to 601 // check every nmethod for dependencies which makes it linear in 602 // the number of methods compiled. For applications with a lot 603 // classes the slow way is too slow. 604 for (Dependencies::DepStream deps(nm); deps.next(); ) { 605 if (deps.type() == Dependencies::call_site_target_value) { 606 // CallSite dependencies are managed on per-CallSite instance basis. 607 oop call_site = deps.argument_oop(0); 608 MethodHandles::add_dependent_nmethod(call_site, nm); 609 } else { 610 InstanceKlass* ik = deps.context_type(); 611 if (ik == nullptr) { 612 continue; // ignore things like evol_method 613 } 614 // record this nmethod as dependent on this klass 615 ik->add_dependent_nmethod(nm); 616 } 617 } 618 NOT_PRODUCT(if (nm != nullptr) note_java_nmethod(nm)); 619 } 620 } 621 // Do verification and logging outside CodeCache_lock. 622 if (nm != nullptr) { 623 // Safepoints in nmethod::verify aren't allowed because nm hasn't been installed yet. 624 DEBUG_ONLY(nm->verify();) 625 nm->log_new_nmethod(); 626 } 627 return nm; 628 } 629 630 // For native wrappers 631 nmethod::nmethod( 632 Method* method, 633 CompilerType type, 634 int nmethod_size, 635 int compile_id, 636 CodeOffsets* offsets, 637 CodeBuffer* code_buffer, 638 int frame_size, 639 ByteSize basic_lock_owner_sp_offset, 640 ByteSize basic_lock_sp_offset, 641 OopMapSet* oop_maps ) 642 : CompiledMethod(method, "native nmethod", type, nmethod_size, sizeof(nmethod), code_buffer, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps, false, true), 643 _compiled_ic_data(nullptr), 644 _is_unlinked(false), 645 _native_receiver_sp_offset(basic_lock_owner_sp_offset), 646 _native_basic_lock_sp_offset(basic_lock_sp_offset), 647 _is_unloading_state(0) 648 { 649 { 650 int scopes_data_offset = 0; 651 int deoptimize_offset = 0; 652 int deoptimize_mh_offset = 0; 653 654 debug_only(NoSafepointVerifier nsv;) 655 assert_locked_or_safepoint(CodeCache_lock); 656 657 init_defaults(); 658 _comp_level = CompLevel_none; 659 _entry_bci = InvocationEntryBci; 660 // We have no exception handler or deopt handler make the 661 // values something that will never match a pc like the nmethod vtable entry 662 _exception_offset = 0; 663 _orig_pc_offset = 0; 664 _gc_epoch = CodeCache::gc_epoch(); 665 666 _consts_offset = content_offset() + code_buffer->total_offset_of(code_buffer->consts()); 667 _stub_offset = content_offset() + code_buffer->total_offset_of(code_buffer->stubs()); 668 _oops_offset = data_offset(); 669 _metadata_offset = _oops_offset + align_up(code_buffer->total_oop_size(), oopSize); 670 scopes_data_offset = _metadata_offset + align_up(code_buffer->total_metadata_size(), wordSize); 671 _scopes_pcs_offset = scopes_data_offset; 672 _dependencies_offset = _scopes_pcs_offset; 673 _handler_table_offset = _dependencies_offset; 674 _nul_chk_table_offset = _handler_table_offset; 675 _skipped_instructions_size = code_buffer->total_skipped_instructions_size(); 676 #if INCLUDE_JVMCI 677 _speculations_offset = _nul_chk_table_offset; 678 _jvmci_data_offset = _speculations_offset; 679 _nmethod_end_offset = _jvmci_data_offset; 680 #else 681 _nmethod_end_offset = _nul_chk_table_offset; 682 #endif 683 _compile_id = compile_id; 684 _entry_point = code_begin() + offsets->value(CodeOffsets::Entry); 685 _verified_entry_point = code_begin() + offsets->value(CodeOffsets::Verified_Entry); 686 687 assert(!method->has_scalarized_args(), "scalarized native wrappers not supported yet"); // for the next 3 fields 688 _inline_entry_point = _entry_point; 689 _verified_inline_entry_point = _verified_entry_point; 690 _verified_inline_ro_entry_point = _verified_entry_point; 691 692 _osr_entry_point = nullptr; 693 _exception_cache = nullptr; 694 _pc_desc_container.reset_to(nullptr); 695 696 _exception_offset = code_offset() + offsets->value(CodeOffsets::Exceptions); 697 698 _scopes_data_begin = (address) this + scopes_data_offset; 699 _deopt_handler_begin = (address) this + deoptimize_offset; 700 _deopt_mh_handler_begin = (address) this + deoptimize_mh_offset; 701 702 code_buffer->copy_code_and_locs_to(this); 703 code_buffer->copy_values_to(this); 704 705 clear_unloading_state(); 706 707 finalize_relocations(); 708 709 Universe::heap()->register_nmethod(this); 710 debug_only(Universe::heap()->verify_nmethod(this)); 711 712 CodeCache::commit(this); 713 } 714 715 if (PrintNativeNMethods || PrintDebugInfo || PrintRelocations || PrintDependencies) { 716 ttyLocker ttyl; // keep the following output all in one block 717 // This output goes directly to the tty, not the compiler log. 718 // To enable tools to match it up with the compilation activity, 719 // be sure to tag this tty output with the compile ID. 720 if (xtty != nullptr) { 721 xtty->begin_head("print_native_nmethod"); 722 xtty->method(_method); 723 xtty->stamp(); 724 xtty->end_head(" address='" INTPTR_FORMAT "'", (intptr_t) this); 725 } 726 // Print the header part, then print the requested information. 727 // This is both handled in decode2(), called via print_code() -> decode() 728 if (PrintNativeNMethods) { 729 tty->print_cr("-------------------------- Assembly (native nmethod) ---------------------------"); 730 print_code(); 731 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 732 #if defined(SUPPORT_DATA_STRUCTS) 733 if (AbstractDisassembler::show_structs()) { 734 if (oop_maps != nullptr) { 735 tty->print("oop maps:"); // oop_maps->print_on(tty) outputs a cr() at the beginning 736 oop_maps->print_on(tty); 737 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 738 } 739 } 740 #endif 741 } else { 742 print(); // print the header part only. 743 } 744 #if defined(SUPPORT_DATA_STRUCTS) 745 if (AbstractDisassembler::show_structs()) { 746 if (PrintRelocations) { 747 print_relocations(); 748 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 749 } 750 } 751 #endif 752 if (xtty != nullptr) { 753 xtty->tail("print_native_nmethod"); 754 } 755 } 756 } 757 758 void* nmethod::operator new(size_t size, int nmethod_size, int comp_level) throw () { 759 return CodeCache::allocate(nmethod_size, CodeCache::get_code_blob_type(comp_level)); 760 } 761 762 void* nmethod::operator new(size_t size, int nmethod_size, bool allow_NonNMethod_space) throw () { 763 // Try MethodNonProfiled and MethodProfiled. 764 void* return_value = CodeCache::allocate(nmethod_size, CodeBlobType::MethodNonProfiled); 765 if (return_value != nullptr || !allow_NonNMethod_space) return return_value; 766 // Try NonNMethod or give up. 767 return CodeCache::allocate(nmethod_size, CodeBlobType::NonNMethod); 768 } 769 770 nmethod::nmethod( 771 Method* method, 772 CompilerType type, 773 int nmethod_size, 774 int compile_id, 775 int entry_bci, 776 CodeOffsets* offsets, 777 int orig_pc_offset, 778 DebugInformationRecorder* debug_info, 779 Dependencies* dependencies, 780 CodeBuffer *code_buffer, 781 int frame_size, 782 OopMapSet* oop_maps, 783 ExceptionHandlerTable* handler_table, 784 ImplicitExceptionTable* nul_chk_table, 785 AbstractCompiler* compiler, 786 CompLevel comp_level 787 #if INCLUDE_JVMCI 788 , char* speculations, 789 int speculations_len, 790 JVMCINMethodData* jvmci_data 791 #endif 792 ) 793 : CompiledMethod(method, "nmethod", type, nmethod_size, sizeof(nmethod), code_buffer, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps, false, true), 794 _compiled_ic_data(nullptr), 795 _is_unlinked(false), 796 _native_receiver_sp_offset(in_ByteSize(-1)), 797 _native_basic_lock_sp_offset(in_ByteSize(-1)), 798 _is_unloading_state(0) 799 { 800 assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR"); 801 { 802 debug_only(NoSafepointVerifier nsv;) 803 assert_locked_or_safepoint(CodeCache_lock); 804 805 _deopt_handler_begin = (address) this; 806 _deopt_mh_handler_begin = (address) this; 807 808 init_defaults(); 809 _entry_bci = entry_bci; 810 _compile_id = compile_id; 811 _comp_level = comp_level; 812 _orig_pc_offset = orig_pc_offset; 813 _gc_epoch = CodeCache::gc_epoch(); 814 815 // Section offsets 816 _consts_offset = content_offset() + code_buffer->total_offset_of(code_buffer->consts()); 817 _stub_offset = content_offset() + code_buffer->total_offset_of(code_buffer->stubs()); 818 set_ctable_begin(header_begin() + _consts_offset); 819 _skipped_instructions_size = code_buffer->total_skipped_instructions_size(); 820 821 #if INCLUDE_JVMCI 822 if (compiler->is_jvmci()) { 823 // JVMCI might not produce any stub sections 824 if (offsets->value(CodeOffsets::Exceptions) != -1) { 825 _exception_offset = code_offset() + offsets->value(CodeOffsets::Exceptions); 826 } else { 827 _exception_offset = -1; 828 } 829 if (offsets->value(CodeOffsets::Deopt) != -1) { 830 _deopt_handler_begin = (address) this + code_offset() + offsets->value(CodeOffsets::Deopt); 831 } else { 832 _deopt_handler_begin = nullptr; 833 } 834 if (offsets->value(CodeOffsets::DeoptMH) != -1) { 835 _deopt_mh_handler_begin = (address) this + code_offset() + offsets->value(CodeOffsets::DeoptMH); 836 } else { 837 _deopt_mh_handler_begin = nullptr; 838 } 839 } else 840 #endif 841 { 842 // Exception handler and deopt handler are in the stub section 843 assert(offsets->value(CodeOffsets::Exceptions) != -1, "must be set"); 844 assert(offsets->value(CodeOffsets::Deopt ) != -1, "must be set"); 845 846 _exception_offset = _stub_offset + offsets->value(CodeOffsets::Exceptions); 847 _deopt_handler_begin = (address) this + _stub_offset + offsets->value(CodeOffsets::Deopt); 848 if (offsets->value(CodeOffsets::DeoptMH) != -1) { 849 _deopt_mh_handler_begin = (address) this + _stub_offset + offsets->value(CodeOffsets::DeoptMH); 850 } else { 851 _deopt_mh_handler_begin = nullptr; 852 } 853 } 854 if (offsets->value(CodeOffsets::UnwindHandler) != -1) { 855 _unwind_handler_offset = code_offset() + offsets->value(CodeOffsets::UnwindHandler); 856 } else { 857 _unwind_handler_offset = -1; 858 } 859 860 _oops_offset = data_offset(); 861 _metadata_offset = _oops_offset + align_up(code_buffer->total_oop_size(), oopSize); 862 int scopes_data_offset = _metadata_offset + align_up(code_buffer->total_metadata_size(), wordSize); 863 864 _scopes_pcs_offset = scopes_data_offset + align_up(debug_info->data_size (), oopSize); 865 _dependencies_offset = _scopes_pcs_offset + adjust_pcs_size(debug_info->pcs_size()); 866 _handler_table_offset = _dependencies_offset + align_up((int)dependencies->size_in_bytes(), oopSize); 867 _nul_chk_table_offset = _handler_table_offset + align_up(handler_table->size_in_bytes(), oopSize); 868 #if INCLUDE_JVMCI 869 _speculations_offset = _nul_chk_table_offset + align_up(nul_chk_table->size_in_bytes(), oopSize); 870 _jvmci_data_offset = _speculations_offset + align_up(speculations_len, oopSize); 871 int jvmci_data_size = compiler->is_jvmci() ? jvmci_data->size() : 0; 872 _nmethod_end_offset = _jvmci_data_offset + align_up(jvmci_data_size, oopSize); 873 #else 874 _nmethod_end_offset = _nul_chk_table_offset + align_up(nul_chk_table->size_in_bytes(), oopSize); 875 #endif 876 _entry_point = code_begin() + offsets->value(CodeOffsets::Entry); 877 _verified_entry_point = code_begin() + offsets->value(CodeOffsets::Verified_Entry); 878 _inline_entry_point = code_begin() + offsets->value(CodeOffsets::Inline_Entry); 879 _verified_inline_entry_point = code_begin() + offsets->value(CodeOffsets::Verified_Inline_Entry); 880 _verified_inline_ro_entry_point = code_begin() + offsets->value(CodeOffsets::Verified_Inline_Entry_RO); 881 _osr_entry_point = code_begin() + offsets->value(CodeOffsets::OSR_Entry); 882 _exception_cache = nullptr; 883 _scopes_data_begin = (address) this + scopes_data_offset; 884 885 _pc_desc_container.reset_to(scopes_pcs_begin()); 886 887 code_buffer->copy_code_and_locs_to(this); 888 // Copy contents of ScopeDescRecorder to nmethod 889 code_buffer->copy_values_to(this); 890 debug_info->copy_to(this); 891 dependencies->copy_to(this); 892 clear_unloading_state(); 893 894 #if INCLUDE_JVMCI 895 if (compiler->is_jvmci()) { 896 // Initialize the JVMCINMethodData object inlined into nm 897 jvmci_nmethod_data()->copy(jvmci_data); 898 } 899 #endif 900 901 finalize_relocations(); 902 903 Universe::heap()->register_nmethod(this); 904 debug_only(Universe::heap()->verify_nmethod(this)); 905 906 CodeCache::commit(this); 907 908 // Copy contents of ExceptionHandlerTable to nmethod 909 handler_table->copy_to(this); 910 nul_chk_table->copy_to(this); 911 912 #if INCLUDE_JVMCI 913 // Copy speculations to nmethod 914 if (speculations_size() != 0) { 915 memcpy(speculations_begin(), speculations, speculations_len); 916 } 917 #endif 918 919 // we use the information of entry points to find out if a method is 920 // static or non static 921 assert(compiler->is_c2() || compiler->is_jvmci() || 922 _method->is_static() == (entry_point() == _verified_entry_point), 923 " entry points must be same for static methods and vice versa"); 924 } 925 } 926 927 // Print a short set of xml attributes to identify this nmethod. The 928 // output should be embedded in some other element. 929 void nmethod::log_identity(xmlStream* log) const { 930 log->print(" compile_id='%d'", compile_id()); 931 const char* nm_kind = compile_kind(); 932 if (nm_kind != nullptr) log->print(" compile_kind='%s'", nm_kind); 933 log->print(" compiler='%s'", compiler_name()); 934 if (TieredCompilation) { 935 log->print(" level='%d'", comp_level()); 936 } 937 #if INCLUDE_JVMCI 938 if (jvmci_nmethod_data() != nullptr) { 939 const char* jvmci_name = jvmci_nmethod_data()->name(); 940 if (jvmci_name != nullptr) { 941 log->print(" jvmci_mirror_name='"); 942 log->text("%s", jvmci_name); 943 log->print("'"); 944 } 945 } 946 #endif 947 } 948 949 950 #define LOG_OFFSET(log, name) \ 951 if (p2i(name##_end()) - p2i(name##_begin())) \ 952 log->print(" " XSTR(name) "_offset='" INTX_FORMAT "'" , \ 953 p2i(name##_begin()) - p2i(this)) 954 955 956 void nmethod::log_new_nmethod() const { 957 if (LogCompilation && xtty != nullptr) { 958 ttyLocker ttyl; 959 xtty->begin_elem("nmethod"); 960 log_identity(xtty); 961 xtty->print(" entry='" INTPTR_FORMAT "' size='%d'", p2i(code_begin()), size()); 962 xtty->print(" address='" INTPTR_FORMAT "'", p2i(this)); 963 964 LOG_OFFSET(xtty, relocation); 965 LOG_OFFSET(xtty, consts); 966 LOG_OFFSET(xtty, insts); 967 LOG_OFFSET(xtty, stub); 968 LOG_OFFSET(xtty, scopes_data); 969 LOG_OFFSET(xtty, scopes_pcs); 970 LOG_OFFSET(xtty, dependencies); 971 LOG_OFFSET(xtty, handler_table); 972 LOG_OFFSET(xtty, nul_chk_table); 973 LOG_OFFSET(xtty, oops); 974 LOG_OFFSET(xtty, metadata); 975 976 xtty->method(method()); 977 xtty->stamp(); 978 xtty->end_elem(); 979 } 980 } 981 982 #undef LOG_OFFSET 983 984 985 // Print out more verbose output usually for a newly created nmethod. 986 void nmethod::print_on(outputStream* st, const char* msg) const { 987 if (st != nullptr) { 988 ttyLocker ttyl; 989 if (WizardMode) { 990 CompileTask::print(st, this, msg, /*short_form:*/ true); 991 st->print_cr(" (" INTPTR_FORMAT ")", p2i(this)); 992 } else { 993 CompileTask::print(st, this, msg, /*short_form:*/ false); 994 } 995 } 996 } 997 998 void nmethod::maybe_print_nmethod(const DirectiveSet* directive) { 999 bool printnmethods = directive->PrintAssemblyOption || directive->PrintNMethodsOption; 1000 if (printnmethods || PrintDebugInfo || PrintRelocations || PrintDependencies || PrintExceptionHandlers) { 1001 print_nmethod(printnmethods); 1002 } 1003 } 1004 1005 void nmethod::print_nmethod(bool printmethod) { 1006 ttyLocker ttyl; // keep the following output all in one block 1007 if (xtty != nullptr) { 1008 xtty->begin_head("print_nmethod"); 1009 log_identity(xtty); 1010 xtty->stamp(); 1011 xtty->end_head(); 1012 } 1013 // Print the header part, then print the requested information. 1014 // This is both handled in decode2(). 1015 if (printmethod) { 1016 ResourceMark m; 1017 if (is_compiled_by_c1()) { 1018 tty->cr(); 1019 tty->print_cr("============================= C1-compiled nmethod =============================="); 1020 } 1021 if (is_compiled_by_jvmci()) { 1022 tty->cr(); 1023 tty->print_cr("=========================== JVMCI-compiled nmethod ============================="); 1024 } 1025 tty->print_cr("----------------------------------- Assembly -----------------------------------"); 1026 decode2(tty); 1027 #if defined(SUPPORT_DATA_STRUCTS) 1028 if (AbstractDisassembler::show_structs()) { 1029 // Print the oops from the underlying CodeBlob as well. 1030 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1031 print_oops(tty); 1032 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1033 print_metadata(tty); 1034 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1035 print_pcs_on(tty); 1036 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1037 if (oop_maps() != nullptr) { 1038 tty->print("oop maps:"); // oop_maps()->print_on(tty) outputs a cr() at the beginning 1039 oop_maps()->print_on(tty); 1040 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1041 } 1042 } 1043 #endif 1044 } else { 1045 print(); // print the header part only. 1046 } 1047 1048 #if defined(SUPPORT_DATA_STRUCTS) 1049 if (AbstractDisassembler::show_structs()) { 1050 methodHandle mh(Thread::current(), _method); 1051 if (printmethod || PrintDebugInfo || CompilerOracle::has_option(mh, CompileCommand::PrintDebugInfo)) { 1052 print_scopes(); 1053 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1054 } 1055 if (printmethod || PrintRelocations || CompilerOracle::has_option(mh, CompileCommand::PrintRelocations)) { 1056 print_relocations(); 1057 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1058 } 1059 if (printmethod || PrintDependencies || CompilerOracle::has_option(mh, CompileCommand::PrintDependencies)) { 1060 print_dependencies_on(tty); 1061 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1062 } 1063 if (printmethod || PrintExceptionHandlers) { 1064 print_handler_table(); 1065 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1066 print_nul_chk_table(); 1067 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1068 } 1069 1070 if (printmethod) { 1071 print_recorded_oops(); 1072 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1073 print_recorded_metadata(); 1074 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "); 1075 } 1076 } 1077 #endif 1078 1079 if (xtty != nullptr) { 1080 xtty->tail("print_nmethod"); 1081 } 1082 } 1083 1084 1085 // Promote one word from an assembly-time handle to a live embedded oop. 1086 inline void nmethod::initialize_immediate_oop(oop* dest, jobject handle) { 1087 if (handle == nullptr || 1088 // As a special case, IC oops are initialized to 1 or -1. 1089 handle == (jobject) Universe::non_oop_word()) { 1090 *(void**)dest = handle; 1091 } else { 1092 *dest = JNIHandles::resolve_non_null(handle); 1093 } 1094 } 1095 1096 1097 // Have to have the same name because it's called by a template 1098 void nmethod::copy_values(GrowableArray<jobject>* array) { 1099 int length = array->length(); 1100 assert((address)(oops_begin() + length) <= (address)oops_end(), "oops big enough"); 1101 oop* dest = oops_begin(); 1102 for (int index = 0 ; index < length; index++) { 1103 initialize_immediate_oop(&dest[index], array->at(index)); 1104 } 1105 1106 // Now we can fix up all the oops in the code. We need to do this 1107 // in the code because the assembler uses jobjects as placeholders. 1108 // The code and relocations have already been initialized by the 1109 // CodeBlob constructor, so it is valid even at this early point to 1110 // iterate over relocations and patch the code. 1111 fix_oop_relocations(nullptr, nullptr, /*initialize_immediates=*/ true); 1112 } 1113 1114 void nmethod::copy_values(GrowableArray<Metadata*>* array) { 1115 int length = array->length(); 1116 assert((address)(metadata_begin() + length) <= (address)metadata_end(), "big enough"); 1117 Metadata** dest = metadata_begin(); 1118 for (int index = 0 ; index < length; index++) { 1119 dest[index] = array->at(index); 1120 } 1121 } 1122 1123 void nmethod::fix_oop_relocations(address begin, address end, bool initialize_immediates) { 1124 // re-patch all oop-bearing instructions, just in case some oops moved 1125 RelocIterator iter(this, begin, end); 1126 while (iter.next()) { 1127 if (iter.type() == relocInfo::oop_type) { 1128 oop_Relocation* reloc = iter.oop_reloc(); 1129 if (initialize_immediates && reloc->oop_is_immediate()) { 1130 oop* dest = reloc->oop_addr(); 1131 jobject obj = *reinterpret_cast<jobject*>(dest); 1132 initialize_immediate_oop(dest, obj); 1133 } 1134 // Refresh the oop-related bits of this instruction. 1135 reloc->fix_oop_relocation(); 1136 } else if (iter.type() == relocInfo::metadata_type) { 1137 metadata_Relocation* reloc = iter.metadata_reloc(); 1138 reloc->fix_metadata_relocation(); 1139 } 1140 } 1141 } 1142 1143 static void install_post_call_nop_displacement(nmethod* nm, address pc) { 1144 NativePostCallNop* nop = nativePostCallNop_at((address) pc); 1145 intptr_t cbaddr = (intptr_t) nm; 1146 intptr_t offset = ((intptr_t) pc) - cbaddr; 1147 1148 int oopmap_slot = nm->oop_maps()->find_slot_for_offset(int((intptr_t) pc - (intptr_t) nm->code_begin())); 1149 if (oopmap_slot < 0) { // this can happen at asynchronous (non-safepoint) stackwalks 1150 log_debug(codecache)("failed to find oopmap for cb: " INTPTR_FORMAT " offset: %d", cbaddr, (int) offset); 1151 } else if (!nop->patch(oopmap_slot, offset)) { 1152 log_debug(codecache)("failed to encode %d %d", oopmap_slot, (int) offset); 1153 } 1154 } 1155 1156 void nmethod::finalize_relocations() { 1157 NoSafepointVerifier nsv; 1158 1159 GrowableArray<NativeMovConstReg*> virtual_call_data; 1160 1161 // Make sure that post call nops fill in nmethod offsets eagerly so 1162 // we don't have to race with deoptimization 1163 RelocIterator iter(this); 1164 while (iter.next()) { 1165 if (iter.type() == relocInfo::virtual_call_type) { 1166 virtual_call_Relocation* r = iter.virtual_call_reloc(); 1167 NativeMovConstReg* value = nativeMovConstReg_at(r->cached_value()); 1168 virtual_call_data.append(value); 1169 } else if (iter.type() == relocInfo::post_call_nop_type) { 1170 post_call_nop_Relocation* const reloc = iter.post_call_nop_reloc(); 1171 address pc = reloc->addr(); 1172 install_post_call_nop_displacement(this, pc); 1173 } 1174 } 1175 1176 if (virtual_call_data.length() > 0) { 1177 // We allocate a block of CompiledICData per nmethod so the GC can purge this faster. 1178 _compiled_ic_data = new CompiledICData[virtual_call_data.length()]; 1179 CompiledICData* next_data = _compiled_ic_data; 1180 1181 for (NativeMovConstReg* value : virtual_call_data) { 1182 value->set_data((intptr_t)next_data); 1183 next_data++; 1184 } 1185 } 1186 } 1187 1188 void nmethod::make_deoptimized() { 1189 if (!Continuations::enabled()) { 1190 // Don't deopt this again. 1191 set_deoptimized_done(); 1192 return; 1193 } 1194 1195 assert(method() == nullptr || can_be_deoptimized(), ""); 1196 1197 CompiledICLocker ml(this); 1198 assert(CompiledICLocker::is_safe(this), "mt unsafe call"); 1199 1200 // If post call nops have been already patched, we can just bail-out. 1201 if (has_been_deoptimized()) { 1202 return; 1203 } 1204 1205 ResourceMark rm; 1206 RelocIterator iter(this, oops_reloc_begin()); 1207 1208 while (iter.next()) { 1209 1210 switch (iter.type()) { 1211 case relocInfo::virtual_call_type: { 1212 CompiledIC *ic = CompiledIC_at(&iter); 1213 address pc = ic->end_of_call(); 1214 NativePostCallNop* nop = nativePostCallNop_at(pc); 1215 if (nop != nullptr) { 1216 nop->make_deopt(); 1217 } 1218 assert(NativeDeoptInstruction::is_deopt_at(pc), "check"); 1219 break; 1220 } 1221 case relocInfo::static_call_type: 1222 case relocInfo::opt_virtual_call_type: { 1223 CompiledDirectCall *csc = CompiledDirectCall::at(iter.reloc()); 1224 address pc = csc->end_of_call(); 1225 NativePostCallNop* nop = nativePostCallNop_at(pc); 1226 //tty->print_cr(" - static pc %p", pc); 1227 if (nop != nullptr) { 1228 nop->make_deopt(); 1229 } 1230 // We can't assert here, there are some calls to stubs / runtime 1231 // that have reloc data and doesn't have a post call NOP. 1232 //assert(NativeDeoptInstruction::is_deopt_at(pc), "check"); 1233 break; 1234 } 1235 default: 1236 break; 1237 } 1238 } 1239 // Don't deopt this again. 1240 set_deoptimized_done(); 1241 } 1242 1243 void nmethod::verify_clean_inline_caches() { 1244 assert(CompiledICLocker::is_safe(this), "mt unsafe call"); 1245 1246 ResourceMark rm; 1247 RelocIterator iter(this, oops_reloc_begin()); 1248 while(iter.next()) { 1249 switch(iter.type()) { 1250 case relocInfo::virtual_call_type: { 1251 CompiledIC *ic = CompiledIC_at(&iter); 1252 CodeBlob *cb = CodeCache::find_blob(ic->destination()); 1253 assert(cb != nullptr, "destination not in CodeBlob?"); 1254 nmethod* nm = cb->as_nmethod_or_null(); 1255 if (nm != nullptr) { 1256 // Verify that inline caches pointing to bad nmethods are clean 1257 if (!nm->is_in_use() || nm->is_unloading()) { 1258 assert(ic->is_clean(), "IC should be clean"); 1259 } 1260 } 1261 break; 1262 } 1263 case relocInfo::static_call_type: 1264 case relocInfo::opt_virtual_call_type: { 1265 CompiledDirectCall *cdc = CompiledDirectCall::at(iter.reloc()); 1266 CodeBlob *cb = CodeCache::find_blob(cdc->destination()); 1267 assert(cb != nullptr, "destination not in CodeBlob?"); 1268 nmethod* nm = cb->as_nmethod_or_null(); 1269 if (nm != nullptr) { 1270 // Verify that inline caches pointing to bad nmethods are clean 1271 if (!nm->is_in_use() || nm->is_unloading() || nm->method()->code() != nm) { 1272 assert(cdc->is_clean(), "IC should be clean"); 1273 } 1274 } 1275 break; 1276 } 1277 default: 1278 break; 1279 } 1280 } 1281 } 1282 1283 void nmethod::mark_as_maybe_on_stack() { 1284 Atomic::store(&_gc_epoch, CodeCache::gc_epoch()); 1285 } 1286 1287 bool nmethod::is_maybe_on_stack() { 1288 // If the condition below is true, it means that the nmethod was found to 1289 // be alive the previous completed marking cycle. 1290 return Atomic::load(&_gc_epoch) >= CodeCache::previous_completed_gc_marking_cycle(); 1291 } 1292 1293 void nmethod::inc_decompile_count() { 1294 if (!is_compiled_by_c2() && !is_compiled_by_jvmci()) return; 1295 // Could be gated by ProfileTraps, but do not bother... 1296 Method* m = method(); 1297 if (m == nullptr) return; 1298 MethodData* mdo = m->method_data(); 1299 if (mdo == nullptr) return; 1300 // There is a benign race here. See comments in methodData.hpp. 1301 mdo->inc_decompile_count(); 1302 } 1303 1304 bool nmethod::try_transition(signed char new_state_int) { 1305 signed char new_state = new_state_int; 1306 assert_lock_strong(CompiledMethod_lock); 1307 signed char old_state = _state; 1308 if (old_state >= new_state) { 1309 // Ensure monotonicity of transitions. 1310 return false; 1311 } 1312 Atomic::store(&_state, new_state); 1313 return true; 1314 } 1315 1316 void nmethod::invalidate_osr_method() { 1317 assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod"); 1318 // Remove from list of active nmethods 1319 if (method() != nullptr) { 1320 method()->method_holder()->remove_osr_nmethod(this); 1321 } 1322 } 1323 1324 void nmethod::log_state_change() const { 1325 if (LogCompilation) { 1326 if (xtty != nullptr) { 1327 ttyLocker ttyl; // keep the following output all in one block 1328 xtty->begin_elem("make_not_entrant thread='" UINTX_FORMAT "'", 1329 os::current_thread_id()); 1330 log_identity(xtty); 1331 xtty->stamp(); 1332 xtty->end_elem(); 1333 } 1334 } 1335 1336 CompileTask::print_ul(this, "made not entrant"); 1337 if (PrintCompilation) { 1338 print_on(tty, "made not entrant"); 1339 } 1340 } 1341 1342 void nmethod::unlink_from_method() { 1343 if (method() != nullptr) { 1344 method()->unlink_code(this); 1345 } 1346 } 1347 1348 // Invalidate code 1349 bool nmethod::make_not_entrant() { 1350 // This can be called while the system is already at a safepoint which is ok 1351 NoSafepointVerifier nsv; 1352 1353 if (is_unloading()) { 1354 // If the nmethod is unloading, then it is already not entrant through 1355 // the nmethod entry barriers. No need to do anything; GC will unload it. 1356 return false; 1357 } 1358 1359 if (Atomic::load(&_state) == not_entrant) { 1360 // Avoid taking the lock if already in required state. 1361 // This is safe from races because the state is an end-state, 1362 // which the nmethod cannot back out of once entered. 1363 // No need for fencing either. 1364 return false; 1365 } 1366 1367 { 1368 // Enter critical section. Does not block for safepoint. 1369 ConditionalMutexLocker ml(CompiledMethod_lock, !CompiledMethod_lock->owned_by_self(), Mutex::_no_safepoint_check_flag); 1370 1371 if (Atomic::load(&_state) == not_entrant) { 1372 // another thread already performed this transition so nothing 1373 // to do, but return false to indicate this. 1374 return false; 1375 } 1376 1377 if (is_osr_method()) { 1378 // This logic is equivalent to the logic below for patching the 1379 // verified entry point of regular methods. 1380 // this effectively makes the osr nmethod not entrant 1381 invalidate_osr_method(); 1382 } else { 1383 // The caller can be calling the method statically or through an inline 1384 // cache call. 1385 NativeJump::patch_verified_entry(entry_point(), verified_entry_point(), 1386 SharedRuntime::get_handle_wrong_method_stub()); 1387 } 1388 1389 if (update_recompile_counts()) { 1390 // Mark the method as decompiled. 1391 inc_decompile_count(); 1392 } 1393 1394 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod(); 1395 if (bs_nm == nullptr || !bs_nm->supports_entry_barrier(this)) { 1396 // If nmethod entry barriers are not supported, we won't mark 1397 // nmethods as on-stack when they become on-stack. So we 1398 // degrade to a less accurate flushing strategy, for now. 1399 mark_as_maybe_on_stack(); 1400 } 1401 1402 // Change state 1403 bool success = try_transition(not_entrant); 1404 assert(success, "Transition can't fail"); 1405 1406 // Log the transition once 1407 log_state_change(); 1408 1409 // Remove nmethod from method. 1410 unlink_from_method(); 1411 1412 } // leave critical region under CompiledMethod_lock 1413 1414 #if INCLUDE_JVMCI 1415 // Invalidate can't occur while holding the Patching lock 1416 JVMCINMethodData* nmethod_data = jvmci_nmethod_data(); 1417 if (nmethod_data != nullptr) { 1418 nmethod_data->invalidate_nmethod_mirror(this); 1419 } 1420 #endif 1421 1422 #ifdef ASSERT 1423 if (is_osr_method() && method() != nullptr) { 1424 // Make sure osr nmethod is invalidated, i.e. not on the list 1425 bool found = method()->method_holder()->remove_osr_nmethod(this); 1426 assert(!found, "osr nmethod should have been invalidated"); 1427 } 1428 #endif 1429 1430 return true; 1431 } 1432 1433 // For concurrent GCs, there must be a handshake between unlink and flush 1434 void nmethod::unlink() { 1435 if (_is_unlinked) { 1436 // Already unlinked. 1437 return; 1438 } 1439 1440 flush_dependencies(); 1441 1442 // unlink_from_method will take the CompiledMethod_lock. 1443 // In this case we don't strictly need it when unlinking nmethods from 1444 // the Method, because it is only concurrently unlinked by 1445 // the entry barrier, which acquires the per nmethod lock. 1446 unlink_from_method(); 1447 1448 if (is_osr_method()) { 1449 invalidate_osr_method(); 1450 } 1451 1452 #if INCLUDE_JVMCI 1453 // Clear the link between this nmethod and a HotSpotNmethod mirror 1454 JVMCINMethodData* nmethod_data = jvmci_nmethod_data(); 1455 if (nmethod_data != nullptr) { 1456 nmethod_data->invalidate_nmethod_mirror(this); 1457 } 1458 #endif 1459 1460 // Post before flushing as jmethodID is being used 1461 post_compiled_method_unload(); 1462 1463 // Register for flushing when it is safe. For concurrent class unloading, 1464 // that would be after the unloading handshake, and for STW class unloading 1465 // that would be when getting back to the VM thread. 1466 ClassUnloadingContext::context()->register_unlinked_nmethod(this); 1467 } 1468 1469 void nmethod::purge(bool free_code_cache_data, bool unregister_nmethod) { 1470 assert(!free_code_cache_data, "must only call not freeing code cache data"); 1471 1472 MutexLocker ml(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1473 1474 // completely deallocate this method 1475 Events::log(Thread::current(), "flushing nmethod " INTPTR_FORMAT, p2i(this)); 1476 log_debug(codecache)("*flushing %s nmethod %3d/" INTPTR_FORMAT ". Live blobs:" UINT32_FORMAT 1477 "/Free CodeCache:" SIZE_FORMAT "Kb", 1478 is_osr_method() ? "osr" : "",_compile_id, p2i(this), CodeCache::blob_count(), 1479 CodeCache::unallocated_capacity(CodeCache::get_code_blob_type(this))/1024); 1480 1481 // We need to deallocate any ExceptionCache data. 1482 // Note that we do not need to grab the nmethod lock for this, it 1483 // better be thread safe if we're disposing of it! 1484 ExceptionCache* ec = exception_cache(); 1485 while(ec != nullptr) { 1486 ExceptionCache* next = ec->next(); 1487 delete ec; 1488 ec = next; 1489 } 1490 1491 delete[] _compiled_ic_data; 1492 1493 if (unregister_nmethod) { 1494 Universe::heap()->unregister_nmethod(this); 1495 } 1496 CodeCache::unregister_old_nmethod(this); 1497 1498 CodeBlob::purge(free_code_cache_data, unregister_nmethod); 1499 } 1500 1501 oop nmethod::oop_at(int index) const { 1502 if (index == 0) { 1503 return nullptr; 1504 } 1505 return NMethodAccess<AS_NO_KEEPALIVE>::oop_load(oop_addr_at(index)); 1506 } 1507 1508 oop nmethod::oop_at_phantom(int index) const { 1509 if (index == 0) { 1510 return nullptr; 1511 } 1512 return NMethodAccess<ON_PHANTOM_OOP_REF>::oop_load(oop_addr_at(index)); 1513 } 1514 1515 // 1516 // Notify all classes this nmethod is dependent on that it is no 1517 // longer dependent. 1518 1519 void nmethod::flush_dependencies() { 1520 if (!has_flushed_dependencies()) { 1521 set_has_flushed_dependencies(); 1522 for (Dependencies::DepStream deps(this); deps.next(); ) { 1523 if (deps.type() == Dependencies::call_site_target_value) { 1524 // CallSite dependencies are managed on per-CallSite instance basis. 1525 oop call_site = deps.argument_oop(0); 1526 MethodHandles::clean_dependency_context(call_site); 1527 } else { 1528 InstanceKlass* ik = deps.context_type(); 1529 if (ik == nullptr) { 1530 continue; // ignore things like evol_method 1531 } 1532 // During GC liveness of dependee determines class that needs to be updated. 1533 // The GC may clean dependency contexts concurrently and in parallel. 1534 ik->clean_dependency_context(); 1535 } 1536 } 1537 } 1538 } 1539 1540 void nmethod::post_compiled_method(CompileTask* task) { 1541 task->mark_success(); 1542 task->set_nm_content_size(content_size()); 1543 task->set_nm_insts_size(insts_size()); 1544 task->set_nm_total_size(total_size()); 1545 1546 // JVMTI -- compiled method notification (must be done outside lock) 1547 post_compiled_method_load_event(); 1548 1549 if (CompilationLog::log() != nullptr) { 1550 CompilationLog::log()->log_nmethod(JavaThread::current(), this); 1551 } 1552 1553 const DirectiveSet* directive = task->directive(); 1554 maybe_print_nmethod(directive); 1555 } 1556 1557 // ------------------------------------------------------------------ 1558 // post_compiled_method_load_event 1559 // new method for install_code() path 1560 // Transfer information from compilation to jvmti 1561 void nmethod::post_compiled_method_load_event(JvmtiThreadState* state) { 1562 // This is a bad time for a safepoint. We don't want 1563 // this nmethod to get unloaded while we're queueing the event. 1564 NoSafepointVerifier nsv; 1565 1566 Method* m = method(); 1567 HOTSPOT_COMPILED_METHOD_LOAD( 1568 (char *) m->klass_name()->bytes(), 1569 m->klass_name()->utf8_length(), 1570 (char *) m->name()->bytes(), 1571 m->name()->utf8_length(), 1572 (char *) m->signature()->bytes(), 1573 m->signature()->utf8_length(), 1574 insts_begin(), insts_size()); 1575 1576 1577 if (JvmtiExport::should_post_compiled_method_load()) { 1578 // Only post unload events if load events are found. 1579 set_load_reported(); 1580 // If a JavaThread hasn't been passed in, let the Service thread 1581 // (which is a real Java thread) post the event 1582 JvmtiDeferredEvent event = JvmtiDeferredEvent::compiled_method_load_event(this); 1583 if (state == nullptr) { 1584 // Execute any barrier code for this nmethod as if it's called, since 1585 // keeping it alive looks like stack walking. 1586 run_nmethod_entry_barrier(); 1587 ServiceThread::enqueue_deferred_event(&event); 1588 } else { 1589 // This enters the nmethod barrier outside in the caller. 1590 state->enqueue_event(&event); 1591 } 1592 } 1593 } 1594 1595 void nmethod::post_compiled_method_unload() { 1596 assert(_method != nullptr, "just checking"); 1597 DTRACE_METHOD_UNLOAD_PROBE(method()); 1598 1599 // If a JVMTI agent has enabled the CompiledMethodUnload event then 1600 // post the event. The Method* will not be valid when this is freed. 1601 1602 // Don't bother posting the unload if the load event wasn't posted. 1603 if (load_reported() && JvmtiExport::should_post_compiled_method_unload()) { 1604 JvmtiDeferredEvent event = 1605 JvmtiDeferredEvent::compiled_method_unload_event( 1606 method()->jmethod_id(), insts_begin()); 1607 ServiceThread::enqueue_deferred_event(&event); 1608 } 1609 } 1610 1611 // Iterate over metadata calling this function. Used by RedefineClasses 1612 void nmethod::metadata_do(MetadataClosure* f) { 1613 { 1614 // Visit all immediate references that are embedded in the instruction stream. 1615 RelocIterator iter(this, oops_reloc_begin()); 1616 while (iter.next()) { 1617 if (iter.type() == relocInfo::metadata_type) { 1618 metadata_Relocation* r = iter.metadata_reloc(); 1619 // In this metadata, we must only follow those metadatas directly embedded in 1620 // the code. Other metadatas (oop_index>0) are seen as part of 1621 // the metadata section below. 1622 assert(1 == (r->metadata_is_immediate()) + 1623 (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()), 1624 "metadata must be found in exactly one place"); 1625 if (r->metadata_is_immediate() && r->metadata_value() != nullptr) { 1626 Metadata* md = r->metadata_value(); 1627 if (md != _method) f->do_metadata(md); 1628 } 1629 } else if (iter.type() == relocInfo::virtual_call_type) { 1630 // Check compiledIC holders associated with this nmethod 1631 ResourceMark rm; 1632 CompiledIC *ic = CompiledIC_at(&iter); 1633 ic->metadata_do(f); 1634 } 1635 } 1636 } 1637 1638 // Visit the metadata section 1639 for (Metadata** p = metadata_begin(); p < metadata_end(); p++) { 1640 if (*p == Universe::non_oop_word() || *p == nullptr) continue; // skip non-oops 1641 Metadata* md = *p; 1642 f->do_metadata(md); 1643 } 1644 1645 // Visit metadata not embedded in the other places. 1646 if (_method != nullptr) f->do_metadata(_method); 1647 } 1648 1649 // Heuristic for nuking nmethods even though their oops are live. 1650 // Main purpose is to reduce code cache pressure and get rid of 1651 // nmethods that don't seem to be all that relevant any longer. 1652 bool nmethod::is_cold() { 1653 if (!MethodFlushing || is_native_method() || is_not_installed()) { 1654 // No heuristic unloading at all 1655 return false; 1656 } 1657 1658 if (!is_maybe_on_stack() && is_not_entrant()) { 1659 // Not entrant nmethods that are not on any stack can just 1660 // be removed 1661 return true; 1662 } 1663 1664 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod(); 1665 if (bs_nm == nullptr || !bs_nm->supports_entry_barrier(this)) { 1666 // On platforms that don't support nmethod entry barriers, we can't 1667 // trust the temporal aspect of the gc epochs. So we can't detect 1668 // cold nmethods on such platforms. 1669 return false; 1670 } 1671 1672 if (!UseCodeCacheFlushing) { 1673 // Bail out if we don't heuristically remove nmethods 1674 return false; 1675 } 1676 1677 // Other code can be phased out more gradually after N GCs 1678 return CodeCache::previous_completed_gc_marking_cycle() > _gc_epoch + 2 * CodeCache::cold_gc_count(); 1679 } 1680 1681 // The _is_unloading_state encodes a tuple comprising the unloading cycle 1682 // and the result of IsUnloadingBehaviour::is_unloading() for that cycle. 1683 // This is the bit layout of the _is_unloading_state byte: 00000CCU 1684 // CC refers to the cycle, which has 2 bits, and U refers to the result of 1685 // IsUnloadingBehaviour::is_unloading() for that unloading cycle. 1686 1687 class IsUnloadingState: public AllStatic { 1688 static const uint8_t _is_unloading_mask = 1; 1689 static const uint8_t _is_unloading_shift = 0; 1690 static const uint8_t _unloading_cycle_mask = 6; 1691 static const uint8_t _unloading_cycle_shift = 1; 1692 1693 static uint8_t set_is_unloading(uint8_t state, bool value) { 1694 state &= (uint8_t)~_is_unloading_mask; 1695 if (value) { 1696 state |= 1 << _is_unloading_shift; 1697 } 1698 assert(is_unloading(state) == value, "unexpected unloading cycle overflow"); 1699 return state; 1700 } 1701 1702 static uint8_t set_unloading_cycle(uint8_t state, uint8_t value) { 1703 state &= (uint8_t)~_unloading_cycle_mask; 1704 state |= (uint8_t)(value << _unloading_cycle_shift); 1705 assert(unloading_cycle(state) == value, "unexpected unloading cycle overflow"); 1706 return state; 1707 } 1708 1709 public: 1710 static bool is_unloading(uint8_t state) { return (state & _is_unloading_mask) >> _is_unloading_shift == 1; } 1711 static uint8_t unloading_cycle(uint8_t state) { return (state & _unloading_cycle_mask) >> _unloading_cycle_shift; } 1712 1713 static uint8_t create(bool is_unloading, uint8_t unloading_cycle) { 1714 uint8_t state = 0; 1715 state = set_is_unloading(state, is_unloading); 1716 state = set_unloading_cycle(state, unloading_cycle); 1717 return state; 1718 } 1719 }; 1720 1721 bool nmethod::is_unloading() { 1722 uint8_t state = Atomic::load(&_is_unloading_state); 1723 bool state_is_unloading = IsUnloadingState::is_unloading(state); 1724 if (state_is_unloading) { 1725 return true; 1726 } 1727 uint8_t state_unloading_cycle = IsUnloadingState::unloading_cycle(state); 1728 uint8_t current_cycle = CodeCache::unloading_cycle(); 1729 if (state_unloading_cycle == current_cycle) { 1730 return false; 1731 } 1732 1733 // The IsUnloadingBehaviour is responsible for calculating if the nmethod 1734 // should be unloaded. This can be either because there is a dead oop, 1735 // or because is_cold() heuristically determines it is time to unload. 1736 state_unloading_cycle = current_cycle; 1737 state_is_unloading = IsUnloadingBehaviour::is_unloading(this); 1738 uint8_t new_state = IsUnloadingState::create(state_is_unloading, state_unloading_cycle); 1739 1740 // Note that if an nmethod has dead oops, everyone will agree that the 1741 // nmethod is_unloading. However, the is_cold heuristics can yield 1742 // different outcomes, so we guard the computed result with a CAS 1743 // to ensure all threads have a shared view of whether an nmethod 1744 // is_unloading or not. 1745 uint8_t found_state = Atomic::cmpxchg(&_is_unloading_state, state, new_state, memory_order_relaxed); 1746 1747 if (found_state == state) { 1748 // First to change state, we win 1749 return state_is_unloading; 1750 } else { 1751 // State already set, so use it 1752 return IsUnloadingState::is_unloading(found_state); 1753 } 1754 } 1755 1756 void nmethod::clear_unloading_state() { 1757 uint8_t state = IsUnloadingState::create(false, CodeCache::unloading_cycle()); 1758 Atomic::store(&_is_unloading_state, state); 1759 } 1760 1761 1762 // This is called at the end of the strong tracing/marking phase of a 1763 // GC to unload an nmethod if it contains otherwise unreachable 1764 // oops or is heuristically found to be not important. 1765 void nmethod::do_unloading(bool unloading_occurred) { 1766 // Make sure the oop's ready to receive visitors 1767 if (is_unloading()) { 1768 unlink(); 1769 } else { 1770 unload_nmethod_caches(unloading_occurred); 1771 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod(); 1772 if (bs_nm != nullptr) { 1773 bs_nm->disarm(this); 1774 } 1775 } 1776 } 1777 1778 void nmethod::oops_do(OopClosure* f, bool allow_dead) { 1779 // Prevent extra code cache walk for platforms that don't have immediate oops. 1780 if (relocInfo::mustIterateImmediateOopsInCode()) { 1781 RelocIterator iter(this, oops_reloc_begin()); 1782 1783 while (iter.next()) { 1784 if (iter.type() == relocInfo::oop_type ) { 1785 oop_Relocation* r = iter.oop_reloc(); 1786 // In this loop, we must only follow those oops directly embedded in 1787 // the code. Other oops (oop_index>0) are seen as part of scopes_oops. 1788 assert(1 == (r->oop_is_immediate()) + 1789 (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()), 1790 "oop must be found in exactly one place"); 1791 if (r->oop_is_immediate() && r->oop_value() != nullptr) { 1792 f->do_oop(r->oop_addr()); 1793 } 1794 } 1795 } 1796 } 1797 1798 // Scopes 1799 // This includes oop constants not inlined in the code stream. 1800 for (oop* p = oops_begin(); p < oops_end(); p++) { 1801 if (*p == Universe::non_oop_word()) continue; // skip non-oops 1802 f->do_oop(p); 1803 } 1804 } 1805 1806 void nmethod::follow_nmethod(OopIterateClosure* cl) { 1807 // Process oops in the nmethod 1808 oops_do(cl); 1809 1810 // CodeCache unloading support 1811 mark_as_maybe_on_stack(); 1812 1813 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod(); 1814 bs_nm->disarm(this); 1815 1816 // There's an assumption made that this function is not used by GCs that 1817 // relocate objects, and therefore we don't call fix_oop_relocations. 1818 } 1819 1820 nmethod* volatile nmethod::_oops_do_mark_nmethods; 1821 1822 void nmethod::oops_do_log_change(const char* state) { 1823 LogTarget(Trace, gc, nmethod) lt; 1824 if (lt.is_enabled()) { 1825 LogStream ls(lt); 1826 CompileTask::print(&ls, this, state, true /* short_form */); 1827 } 1828 } 1829 1830 bool nmethod::oops_do_try_claim() { 1831 if (oops_do_try_claim_weak_request()) { 1832 nmethod* result = oops_do_try_add_to_list_as_weak_done(); 1833 assert(result == nullptr, "adding to global list as weak done must always succeed."); 1834 return true; 1835 } 1836 return false; 1837 } 1838 1839 bool nmethod::oops_do_try_claim_weak_request() { 1840 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint"); 1841 1842 if ((_oops_do_mark_link == nullptr) && 1843 (Atomic::replace_if_null(&_oops_do_mark_link, mark_link(this, claim_weak_request_tag)))) { 1844 oops_do_log_change("oops_do, mark weak request"); 1845 return true; 1846 } 1847 return false; 1848 } 1849 1850 void nmethod::oops_do_set_strong_done(nmethod* old_head) { 1851 _oops_do_mark_link = mark_link(old_head, claim_strong_done_tag); 1852 } 1853 1854 nmethod::oops_do_mark_link* nmethod::oops_do_try_claim_strong_done() { 1855 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint"); 1856 1857 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)); 1858 if (old_next == nullptr) { 1859 oops_do_log_change("oops_do, mark strong done"); 1860 } 1861 return old_next; 1862 } 1863 1864 nmethod::oops_do_mark_link* nmethod::oops_do_try_add_strong_request(nmethod::oops_do_mark_link* next) { 1865 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint"); 1866 assert(next == mark_link(this, claim_weak_request_tag), "Should be claimed as weak"); 1867 1868 oops_do_mark_link* old_next = Atomic::cmpxchg(&_oops_do_mark_link, next, mark_link(this, claim_strong_request_tag)); 1869 if (old_next == next) { 1870 oops_do_log_change("oops_do, mark strong request"); 1871 } 1872 return old_next; 1873 } 1874 1875 bool nmethod::oops_do_try_claim_weak_done_as_strong_done(nmethod::oops_do_mark_link* next) { 1876 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint"); 1877 assert(extract_state(next) == claim_weak_done_tag, "Should be claimed as weak done"); 1878 1879 oops_do_mark_link* old_next = Atomic::cmpxchg(&_oops_do_mark_link, next, mark_link(extract_nmethod(next), claim_strong_done_tag)); 1880 if (old_next == next) { 1881 oops_do_log_change("oops_do, mark weak done -> mark strong done"); 1882 return true; 1883 } 1884 return false; 1885 } 1886 1887 nmethod* nmethod::oops_do_try_add_to_list_as_weak_done() { 1888 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint"); 1889 1890 assert(extract_state(_oops_do_mark_link) == claim_weak_request_tag || 1891 extract_state(_oops_do_mark_link) == claim_strong_request_tag, 1892 "must be but is nmethod " PTR_FORMAT " %u", p2i(extract_nmethod(_oops_do_mark_link)), extract_state(_oops_do_mark_link)); 1893 1894 nmethod* old_head = Atomic::xchg(&_oops_do_mark_nmethods, this); 1895 // Self-loop if needed. 1896 if (old_head == nullptr) { 1897 old_head = this; 1898 } 1899 // Try to install end of list and weak done tag. 1900 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)) { 1901 oops_do_log_change("oops_do, mark weak done"); 1902 return nullptr; 1903 } else { 1904 return old_head; 1905 } 1906 } 1907 1908 void nmethod::oops_do_add_to_list_as_strong_done() { 1909 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint"); 1910 1911 nmethod* old_head = Atomic::xchg(&_oops_do_mark_nmethods, this); 1912 // Self-loop if needed. 1913 if (old_head == nullptr) { 1914 old_head = this; 1915 } 1916 assert(_oops_do_mark_link == mark_link(this, claim_strong_done_tag), "must be but is nmethod " PTR_FORMAT " state %u", 1917 p2i(extract_nmethod(_oops_do_mark_link)), extract_state(_oops_do_mark_link)); 1918 1919 oops_do_set_strong_done(old_head); 1920 } 1921 1922 void nmethod::oops_do_process_weak(OopsDoProcessor* p) { 1923 if (!oops_do_try_claim_weak_request()) { 1924 // Failed to claim for weak processing. 1925 oops_do_log_change("oops_do, mark weak request fail"); 1926 return; 1927 } 1928 1929 p->do_regular_processing(this); 1930 1931 nmethod* old_head = oops_do_try_add_to_list_as_weak_done(); 1932 if (old_head == nullptr) { 1933 return; 1934 } 1935 oops_do_log_change("oops_do, mark weak done fail"); 1936 // Adding to global list failed, another thread added a strong request. 1937 assert(extract_state(_oops_do_mark_link) == claim_strong_request_tag, 1938 "must be but is %u", extract_state(_oops_do_mark_link)); 1939 1940 oops_do_log_change("oops_do, mark weak request -> mark strong done"); 1941 1942 oops_do_set_strong_done(old_head); 1943 // Do missing strong processing. 1944 p->do_remaining_strong_processing(this); 1945 } 1946 1947 void nmethod::oops_do_process_strong(OopsDoProcessor* p) { 1948 oops_do_mark_link* next_raw = oops_do_try_claim_strong_done(); 1949 if (next_raw == nullptr) { 1950 p->do_regular_processing(this); 1951 oops_do_add_to_list_as_strong_done(); 1952 return; 1953 } 1954 // Claim failed. Figure out why and handle it. 1955 if (oops_do_has_weak_request(next_raw)) { 1956 oops_do_mark_link* old = next_raw; 1957 // Claim failed because being weak processed (state == "weak request"). 1958 // Try to request deferred strong processing. 1959 next_raw = oops_do_try_add_strong_request(old); 1960 if (next_raw == old) { 1961 // Successfully requested deferred strong processing. 1962 return; 1963 } 1964 // Failed because of a concurrent transition. No longer in "weak request" state. 1965 } 1966 if (oops_do_has_any_strong_state(next_raw)) { 1967 // Already claimed for strong processing or requested for such. 1968 return; 1969 } 1970 if (oops_do_try_claim_weak_done_as_strong_done(next_raw)) { 1971 // Successfully claimed "weak done" as "strong done". Do the missing marking. 1972 p->do_remaining_strong_processing(this); 1973 return; 1974 } 1975 // Claim failed, some other thread got it. 1976 } 1977 1978 void nmethod::oops_do_marking_prologue() { 1979 assert_at_safepoint(); 1980 1981 log_trace(gc, nmethod)("oops_do_marking_prologue"); 1982 assert(_oops_do_mark_nmethods == nullptr, "must be empty"); 1983 } 1984 1985 void nmethod::oops_do_marking_epilogue() { 1986 assert_at_safepoint(); 1987 1988 nmethod* next = _oops_do_mark_nmethods; 1989 _oops_do_mark_nmethods = nullptr; 1990 if (next != nullptr) { 1991 nmethod* cur; 1992 do { 1993 cur = next; 1994 next = extract_nmethod(cur->_oops_do_mark_link); 1995 cur->_oops_do_mark_link = nullptr; 1996 DEBUG_ONLY(cur->verify_oop_relocations()); 1997 1998 LogTarget(Trace, gc, nmethod) lt; 1999 if (lt.is_enabled()) { 2000 LogStream ls(lt); 2001 CompileTask::print(&ls, cur, "oops_do, unmark", /*short_form:*/ true); 2002 } 2003 // End if self-loop has been detected. 2004 } while (cur != next); 2005 } 2006 log_trace(gc, nmethod)("oops_do_marking_epilogue"); 2007 } 2008 2009 inline bool includes(void* p, void* from, void* to) { 2010 return from <= p && p < to; 2011 } 2012 2013 2014 void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) { 2015 assert(count >= 2, "must be sentinel values, at least"); 2016 2017 #ifdef ASSERT 2018 // must be sorted and unique; we do a binary search in find_pc_desc() 2019 int prev_offset = pcs[0].pc_offset(); 2020 assert(prev_offset == PcDesc::lower_offset_limit, 2021 "must start with a sentinel"); 2022 for (int i = 1; i < count; i++) { 2023 int this_offset = pcs[i].pc_offset(); 2024 assert(this_offset > prev_offset, "offsets must be sorted"); 2025 prev_offset = this_offset; 2026 } 2027 assert(prev_offset == PcDesc::upper_offset_limit, 2028 "must end with a sentinel"); 2029 #endif //ASSERT 2030 2031 // Search for MethodHandle invokes and tag the nmethod. 2032 for (int i = 0; i < count; i++) { 2033 if (pcs[i].is_method_handle_invoke()) { 2034 set_has_method_handle_invokes(true); 2035 break; 2036 } 2037 } 2038 assert(has_method_handle_invokes() == (_deopt_mh_handler_begin != nullptr), "must have deopt mh handler"); 2039 2040 int size = count * sizeof(PcDesc); 2041 assert(scopes_pcs_size() >= size, "oob"); 2042 memcpy(scopes_pcs_begin(), pcs, size); 2043 2044 // Adjust the final sentinel downward. 2045 PcDesc* last_pc = &scopes_pcs_begin()[count-1]; 2046 assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity"); 2047 last_pc->set_pc_offset(content_size() + 1); 2048 for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) { 2049 // Fill any rounding gaps with copies of the last record. 2050 last_pc[1] = last_pc[0]; 2051 } 2052 // The following assert could fail if sizeof(PcDesc) is not 2053 // an integral multiple of oopSize (the rounding term). 2054 // If it fails, change the logic to always allocate a multiple 2055 // of sizeof(PcDesc), and fill unused words with copies of *last_pc. 2056 assert(last_pc + 1 == scopes_pcs_end(), "must match exactly"); 2057 } 2058 2059 void nmethod::copy_scopes_data(u_char* buffer, int size) { 2060 assert(scopes_data_size() >= size, "oob"); 2061 memcpy(scopes_data_begin(), buffer, size); 2062 } 2063 2064 #ifdef ASSERT 2065 static PcDesc* linear_search(const PcDescSearch& search, int pc_offset, bool approximate) { 2066 PcDesc* lower = search.scopes_pcs_begin(); 2067 PcDesc* upper = search.scopes_pcs_end(); 2068 lower += 1; // exclude initial sentinel 2069 PcDesc* res = nullptr; 2070 for (PcDesc* p = lower; p < upper; p++) { 2071 NOT_PRODUCT(--pc_nmethod_stats.pc_desc_tests); // don't count this call to match_desc 2072 if (match_desc(p, pc_offset, approximate)) { 2073 if (res == nullptr) 2074 res = p; 2075 else 2076 res = (PcDesc*) badAddress; 2077 } 2078 } 2079 return res; 2080 } 2081 #endif 2082 2083 2084 // Finds a PcDesc with real-pc equal to "pc" 2085 PcDesc* PcDescContainer::find_pc_desc_internal(address pc, bool approximate, const PcDescSearch& search) { 2086 address base_address = search.code_begin(); 2087 if ((pc < base_address) || 2088 (pc - base_address) >= (ptrdiff_t) PcDesc::upper_offset_limit) { 2089 return nullptr; // PC is wildly out of range 2090 } 2091 int pc_offset = (int) (pc - base_address); 2092 2093 // Check the PcDesc cache if it contains the desired PcDesc 2094 // (This as an almost 100% hit rate.) 2095 PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate); 2096 if (res != nullptr) { 2097 assert(res == linear_search(search, pc_offset, approximate), "cache ok"); 2098 return res; 2099 } 2100 2101 // Fallback algorithm: quasi-linear search for the PcDesc 2102 // Find the last pc_offset less than the given offset. 2103 // The successor must be the required match, if there is a match at all. 2104 // (Use a fixed radix to avoid expensive affine pointer arithmetic.) 2105 PcDesc* lower = search.scopes_pcs_begin(); 2106 PcDesc* upper = search.scopes_pcs_end(); 2107 upper -= 1; // exclude final sentinel 2108 if (lower >= upper) return nullptr; // native method; no PcDescs at all 2109 2110 #define assert_LU_OK \ 2111 /* invariant on lower..upper during the following search: */ \ 2112 assert(lower->pc_offset() < pc_offset, "sanity"); \ 2113 assert(upper->pc_offset() >= pc_offset, "sanity") 2114 assert_LU_OK; 2115 2116 // Use the last successful return as a split point. 2117 PcDesc* mid = _pc_desc_cache.last_pc_desc(); 2118 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches); 2119 if (mid->pc_offset() < pc_offset) { 2120 lower = mid; 2121 } else { 2122 upper = mid; 2123 } 2124 2125 // Take giant steps at first (4096, then 256, then 16, then 1) 2126 const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ debug_only(-1); 2127 const int RADIX = (1 << LOG2_RADIX); 2128 for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) { 2129 while ((mid = lower + step) < upper) { 2130 assert_LU_OK; 2131 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches); 2132 if (mid->pc_offset() < pc_offset) { 2133 lower = mid; 2134 } else { 2135 upper = mid; 2136 break; 2137 } 2138 } 2139 assert_LU_OK; 2140 } 2141 2142 // Sneak up on the value with a linear search of length ~16. 2143 while (true) { 2144 assert_LU_OK; 2145 mid = lower + 1; 2146 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches); 2147 if (mid->pc_offset() < pc_offset) { 2148 lower = mid; 2149 } else { 2150 upper = mid; 2151 break; 2152 } 2153 } 2154 #undef assert_LU_OK 2155 2156 if (match_desc(upper, pc_offset, approximate)) { 2157 assert(upper == linear_search(search, pc_offset, approximate), "search ok"); 2158 if (!Thread::current_in_asgct()) { 2159 // we don't want to modify the cache if we're in ASGCT 2160 // which is typically called in a signal handler 2161 _pc_desc_cache.add_pc_desc(upper); 2162 } 2163 return upper; 2164 } else { 2165 assert(nullptr == linear_search(search, pc_offset, approximate), "search ok"); 2166 return nullptr; 2167 } 2168 } 2169 2170 bool nmethod::check_dependency_on(DepChange& changes) { 2171 // What has happened: 2172 // 1) a new class dependee has been added 2173 // 2) dependee and all its super classes have been marked 2174 bool found_check = false; // set true if we are upset 2175 for (Dependencies::DepStream deps(this); deps.next(); ) { 2176 // Evaluate only relevant dependencies. 2177 if (deps.spot_check_dependency_at(changes) != nullptr) { 2178 found_check = true; 2179 NOT_DEBUG(break); 2180 } 2181 } 2182 return found_check; 2183 } 2184 2185 // Called from mark_for_deoptimization, when dependee is invalidated. 2186 bool nmethod::is_dependent_on_method(Method* dependee) { 2187 for (Dependencies::DepStream deps(this); deps.next(); ) { 2188 if (deps.type() != Dependencies::evol_method) 2189 continue; 2190 Method* method = deps.method_argument(0); 2191 if (method == dependee) return true; 2192 } 2193 return false; 2194 } 2195 2196 void nmethod_init() { 2197 // make sure you didn't forget to adjust the filler fields 2198 assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word"); 2199 } 2200 2201 // ----------------------------------------------------------------------------- 2202 // Verification 2203 2204 class VerifyOopsClosure: public OopClosure { 2205 nmethod* _nm; 2206 bool _ok; 2207 public: 2208 VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { } 2209 bool ok() { return _ok; } 2210 virtual void do_oop(oop* p) { 2211 if (oopDesc::is_oop_or_null(*p)) return; 2212 // Print diagnostic information before calling print_nmethod(). 2213 // Assertions therein might prevent call from returning. 2214 tty->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)", 2215 p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm)); 2216 if (_ok) { 2217 _nm->print_nmethod(true); 2218 _ok = false; 2219 } 2220 } 2221 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); } 2222 }; 2223 2224 class VerifyMetadataClosure: public MetadataClosure { 2225 public: 2226 void do_metadata(Metadata* md) { 2227 if (md->is_method()) { 2228 Method* method = (Method*)md; 2229 assert(!method->is_old(), "Should not be installing old methods"); 2230 } 2231 } 2232 }; 2233 2234 2235 void nmethod::verify() { 2236 if (is_not_entrant()) 2237 return; 2238 2239 // Make sure all the entry points are correctly aligned for patching. 2240 NativeJump::check_verified_entry_alignment(entry_point(), verified_entry_point()); 2241 2242 // assert(oopDesc::is_oop(method()), "must be valid"); 2243 2244 ResourceMark rm; 2245 2246 if (!CodeCache::contains(this)) { 2247 fatal("nmethod at " INTPTR_FORMAT " not in zone", p2i(this)); 2248 } 2249 2250 if(is_native_method() ) 2251 return; 2252 2253 nmethod* nm = CodeCache::find_nmethod(verified_entry_point()); 2254 if (nm != this) { 2255 fatal("findNMethod did not find this nmethod (" INTPTR_FORMAT ")", p2i(this)); 2256 } 2257 2258 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) { 2259 if (! p->verify(this)) { 2260 tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", p2i(this)); 2261 } 2262 } 2263 2264 #ifdef ASSERT 2265 #if INCLUDE_JVMCI 2266 { 2267 // Verify that implicit exceptions that deoptimize have a PcDesc and OopMap 2268 ImmutableOopMapSet* oms = oop_maps(); 2269 ImplicitExceptionTable implicit_table(this); 2270 for (uint i = 0; i < implicit_table.len(); i++) { 2271 int exec_offset = (int) implicit_table.get_exec_offset(i); 2272 if (implicit_table.get_exec_offset(i) == implicit_table.get_cont_offset(i)) { 2273 assert(pc_desc_at(code_begin() + exec_offset) != nullptr, "missing PcDesc"); 2274 bool found = false; 2275 for (int i = 0, imax = oms->count(); i < imax; i++) { 2276 if (oms->pair_at(i)->pc_offset() == exec_offset) { 2277 found = true; 2278 break; 2279 } 2280 } 2281 assert(found, "missing oopmap"); 2282 } 2283 } 2284 } 2285 #endif 2286 #endif 2287 2288 VerifyOopsClosure voc(this); 2289 oops_do(&voc); 2290 assert(voc.ok(), "embedded oops must be OK"); 2291 Universe::heap()->verify_nmethod(this); 2292 2293 assert(_oops_do_mark_link == nullptr, "_oops_do_mark_link for %s should be nullptr but is " PTR_FORMAT, 2294 nm->method()->external_name(), p2i(_oops_do_mark_link)); 2295 verify_scopes(); 2296 2297 CompiledICLocker nm_verify(this); 2298 VerifyMetadataClosure vmc; 2299 metadata_do(&vmc); 2300 } 2301 2302 2303 void nmethod::verify_interrupt_point(address call_site, bool is_inline_cache) { 2304 2305 // Verify IC only when nmethod installation is finished. 2306 if (!is_not_installed()) { 2307 if (CompiledICLocker::is_safe(this)) { 2308 if (is_inline_cache) { 2309 CompiledIC_at(this, call_site); 2310 } else { 2311 CompiledDirectCall::at(call_site); 2312 } 2313 } else { 2314 CompiledICLocker ml_verify(this); 2315 if (is_inline_cache) { 2316 CompiledIC_at(this, call_site); 2317 } else { 2318 CompiledDirectCall::at(call_site); 2319 } 2320 } 2321 } 2322 2323 HandleMark hm(Thread::current()); 2324 2325 PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address()); 2326 assert(pd != nullptr, "PcDesc must exist"); 2327 for (ScopeDesc* sd = new ScopeDesc(this, pd); 2328 !sd->is_top(); sd = sd->sender()) { 2329 sd->verify(); 2330 } 2331 } 2332 2333 void nmethod::verify_scopes() { 2334 if( !method() ) return; // Runtime stubs have no scope 2335 if (method()->is_native()) return; // Ignore stub methods. 2336 // iterate through all interrupt point 2337 // and verify the debug information is valid. 2338 RelocIterator iter((nmethod*)this); 2339 while (iter.next()) { 2340 address stub = nullptr; 2341 switch (iter.type()) { 2342 case relocInfo::virtual_call_type: 2343 verify_interrupt_point(iter.addr(), true /* is_inline_cache */); 2344 break; 2345 case relocInfo::opt_virtual_call_type: 2346 stub = iter.opt_virtual_call_reloc()->static_stub(); 2347 verify_interrupt_point(iter.addr(), false /* is_inline_cache */); 2348 break; 2349 case relocInfo::static_call_type: 2350 stub = iter.static_call_reloc()->static_stub(); 2351 verify_interrupt_point(iter.addr(), false /* is_inline_cache */); 2352 break; 2353 case relocInfo::runtime_call_type: 2354 case relocInfo::runtime_call_w_cp_type: { 2355 address destination = iter.reloc()->value(); 2356 // Right now there is no way to find out which entries support 2357 // an interrupt point. It would be nice if we had this 2358 // information in a table. 2359 break; 2360 } 2361 default: 2362 break; 2363 } 2364 assert(stub == nullptr || stub_contains(stub), "static call stub outside stub section"); 2365 } 2366 } 2367 2368 2369 // ----------------------------------------------------------------------------- 2370 // Printing operations 2371 2372 void nmethod::print() const { 2373 ttyLocker ttyl; // keep the following output all in one block 2374 print(tty); 2375 } 2376 2377 void nmethod::print(outputStream* st) const { 2378 ResourceMark rm; 2379 2380 st->print("Compiled method "); 2381 2382 if (is_compiled_by_c1()) { 2383 st->print("(c1) "); 2384 } else if (is_compiled_by_c2()) { 2385 st->print("(c2) "); 2386 } else if (is_compiled_by_jvmci()) { 2387 st->print("(JVMCI) "); 2388 } else { 2389 st->print("(n/a) "); 2390 } 2391 2392 print_on(st, nullptr); 2393 2394 if (WizardMode) { 2395 st->print("((nmethod*) " INTPTR_FORMAT ") ", p2i(this)); 2396 st->print(" for method " INTPTR_FORMAT , p2i(method())); 2397 st->print(" { "); 2398 st->print_cr("%s ", state()); 2399 st->print_cr("}:"); 2400 } 2401 if (size () > 0) st->print_cr(" total in heap [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2402 p2i(this), 2403 p2i(this) + size(), 2404 size()); 2405 if (relocation_size () > 0) st->print_cr(" relocation [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2406 p2i(relocation_begin()), 2407 p2i(relocation_end()), 2408 relocation_size()); 2409 if (consts_size () > 0) st->print_cr(" constants [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2410 p2i(consts_begin()), 2411 p2i(consts_end()), 2412 consts_size()); 2413 if (insts_size () > 0) st->print_cr(" main code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2414 p2i(insts_begin()), 2415 p2i(insts_end()), 2416 insts_size()); 2417 if (stub_size () > 0) st->print_cr(" stub code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2418 p2i(stub_begin()), 2419 p2i(stub_end()), 2420 stub_size()); 2421 if (oops_size () > 0) st->print_cr(" oops [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2422 p2i(oops_begin()), 2423 p2i(oops_end()), 2424 oops_size()); 2425 if (metadata_size () > 0) st->print_cr(" metadata [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2426 p2i(metadata_begin()), 2427 p2i(metadata_end()), 2428 metadata_size()); 2429 if (scopes_data_size () > 0) st->print_cr(" scopes data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2430 p2i(scopes_data_begin()), 2431 p2i(scopes_data_end()), 2432 scopes_data_size()); 2433 if (scopes_pcs_size () > 0) st->print_cr(" scopes pcs [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2434 p2i(scopes_pcs_begin()), 2435 p2i(scopes_pcs_end()), 2436 scopes_pcs_size()); 2437 if (dependencies_size () > 0) st->print_cr(" dependencies [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2438 p2i(dependencies_begin()), 2439 p2i(dependencies_end()), 2440 dependencies_size()); 2441 if (handler_table_size() > 0) st->print_cr(" handler table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2442 p2i(handler_table_begin()), 2443 p2i(handler_table_end()), 2444 handler_table_size()); 2445 if (nul_chk_table_size() > 0) st->print_cr(" nul chk table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2446 p2i(nul_chk_table_begin()), 2447 p2i(nul_chk_table_end()), 2448 nul_chk_table_size()); 2449 #if INCLUDE_JVMCI 2450 if (speculations_size () > 0) st->print_cr(" speculations [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2451 p2i(speculations_begin()), 2452 p2i(speculations_end()), 2453 speculations_size()); 2454 if (jvmci_data_size () > 0) st->print_cr(" JVMCI data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2455 p2i(jvmci_data_begin()), 2456 p2i(jvmci_data_end()), 2457 jvmci_data_size()); 2458 #endif 2459 } 2460 2461 void nmethod::print_code() { 2462 ResourceMark m; 2463 ttyLocker ttyl; 2464 // Call the specialized decode method of this class. 2465 decode(tty); 2466 } 2467 2468 #ifndef PRODUCT // called InstanceKlass methods are available only then. Declared as PRODUCT_RETURN 2469 2470 void nmethod::print_dependencies_on(outputStream* out) { 2471 ResourceMark rm; 2472 stringStream st; 2473 st.print_cr("Dependencies:"); 2474 for (Dependencies::DepStream deps(this); deps.next(); ) { 2475 deps.print_dependency(&st); 2476 InstanceKlass* ctxk = deps.context_type(); 2477 if (ctxk != nullptr) { 2478 if (ctxk->is_dependent_nmethod(this)) { 2479 st.print_cr(" [nmethod<=klass]%s", ctxk->external_name()); 2480 } 2481 } 2482 deps.log_dependency(); // put it into the xml log also 2483 } 2484 out->print_raw(st.as_string()); 2485 } 2486 #endif 2487 2488 #if defined(SUPPORT_DATA_STRUCTS) 2489 2490 // Print the oops from the underlying CodeBlob. 2491 void nmethod::print_oops(outputStream* st) { 2492 ResourceMark m; 2493 st->print("Oops:"); 2494 if (oops_begin() < oops_end()) { 2495 st->cr(); 2496 for (oop* p = oops_begin(); p < oops_end(); p++) { 2497 Disassembler::print_location((unsigned char*)p, (unsigned char*)oops_begin(), (unsigned char*)oops_end(), st, true, false); 2498 st->print(PTR_FORMAT " ", *((uintptr_t*)p)); 2499 if (Universe::contains_non_oop_word(p)) { 2500 st->print_cr("NON_OOP"); 2501 continue; // skip non-oops 2502 } 2503 if (*p == nullptr) { 2504 st->print_cr("nullptr-oop"); 2505 continue; // skip non-oops 2506 } 2507 (*p)->print_value_on(st); 2508 st->cr(); 2509 } 2510 } else { 2511 st->print_cr(" <list empty>"); 2512 } 2513 } 2514 2515 // Print metadata pool. 2516 void nmethod::print_metadata(outputStream* st) { 2517 ResourceMark m; 2518 st->print("Metadata:"); 2519 if (metadata_begin() < metadata_end()) { 2520 st->cr(); 2521 for (Metadata** p = metadata_begin(); p < metadata_end(); p++) { 2522 Disassembler::print_location((unsigned char*)p, (unsigned char*)metadata_begin(), (unsigned char*)metadata_end(), st, true, false); 2523 st->print(PTR_FORMAT " ", *((uintptr_t*)p)); 2524 if (*p && *p != Universe::non_oop_word()) { 2525 (*p)->print_value_on(st); 2526 } 2527 st->cr(); 2528 } 2529 } else { 2530 st->print_cr(" <list empty>"); 2531 } 2532 } 2533 2534 #ifndef PRODUCT // ScopeDesc::print_on() is available only then. Declared as PRODUCT_RETURN 2535 void nmethod::print_scopes_on(outputStream* st) { 2536 // Find the first pc desc for all scopes in the code and print it. 2537 ResourceMark rm; 2538 st->print("scopes:"); 2539 if (scopes_pcs_begin() < scopes_pcs_end()) { 2540 st->cr(); 2541 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) { 2542 if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null) 2543 continue; 2544 2545 ScopeDesc* sd = scope_desc_at(p->real_pc(this)); 2546 while (sd != nullptr) { 2547 sd->print_on(st, p); // print output ends with a newline 2548 sd = sd->sender(); 2549 } 2550 } 2551 } else { 2552 st->print_cr(" <list empty>"); 2553 } 2554 } 2555 #endif 2556 2557 #ifndef PRODUCT // RelocIterator does support printing only then. 2558 void nmethod::print_relocations() { 2559 ResourceMark m; // in case methods get printed via the debugger 2560 tty->print_cr("relocations:"); 2561 RelocIterator iter(this); 2562 iter.print(); 2563 } 2564 #endif 2565 2566 void nmethod::print_pcs_on(outputStream* st) { 2567 ResourceMark m; // in case methods get printed via debugger 2568 st->print("pc-bytecode offsets:"); 2569 if (scopes_pcs_begin() < scopes_pcs_end()) { 2570 st->cr(); 2571 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) { 2572 p->print_on(st, this); // print output ends with a newline 2573 } 2574 } else { 2575 st->print_cr(" <list empty>"); 2576 } 2577 } 2578 2579 void nmethod::print_handler_table() { 2580 ExceptionHandlerTable(this).print(code_begin()); 2581 } 2582 2583 void nmethod::print_nul_chk_table() { 2584 ImplicitExceptionTable(this).print(code_begin()); 2585 } 2586 2587 void nmethod::print_recorded_oop(int log_n, int i) { 2588 void* value; 2589 2590 if (i == 0) { 2591 value = nullptr; 2592 } else { 2593 // Be careful around non-oop words. Don't create an oop 2594 // with that value, or it will assert in verification code. 2595 if (Universe::contains_non_oop_word(oop_addr_at(i))) { 2596 value = Universe::non_oop_word(); 2597 } else { 2598 value = oop_at(i); 2599 } 2600 } 2601 2602 tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(value)); 2603 2604 if (value == Universe::non_oop_word()) { 2605 tty->print("non-oop word"); 2606 } else { 2607 if (value == 0) { 2608 tty->print("nullptr-oop"); 2609 } else { 2610 oop_at(i)->print_value_on(tty); 2611 } 2612 } 2613 2614 tty->cr(); 2615 } 2616 2617 void nmethod::print_recorded_oops() { 2618 const int n = oops_count(); 2619 const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6; 2620 tty->print("Recorded oops:"); 2621 if (n > 0) { 2622 tty->cr(); 2623 for (int i = 0; i < n; i++) { 2624 print_recorded_oop(log_n, i); 2625 } 2626 } else { 2627 tty->print_cr(" <list empty>"); 2628 } 2629 } 2630 2631 void nmethod::print_recorded_metadata() { 2632 const int n = metadata_count(); 2633 const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6; 2634 tty->print("Recorded metadata:"); 2635 if (n > 0) { 2636 tty->cr(); 2637 for (int i = 0; i < n; i++) { 2638 Metadata* m = metadata_at(i); 2639 tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(m)); 2640 if (m == (Metadata*)Universe::non_oop_word()) { 2641 tty->print("non-metadata word"); 2642 } else if (m == nullptr) { 2643 tty->print("nullptr-oop"); 2644 } else { 2645 Metadata::print_value_on_maybe_null(tty, m); 2646 } 2647 tty->cr(); 2648 } 2649 } else { 2650 tty->print_cr(" <list empty>"); 2651 } 2652 } 2653 #endif 2654 2655 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY) 2656 2657 void nmethod::print_constant_pool(outputStream* st) { 2658 //----------------------------------- 2659 //---< Print the constant pool >--- 2660 //----------------------------------- 2661 int consts_size = this->consts_size(); 2662 if ( consts_size > 0 ) { 2663 unsigned char* cstart = this->consts_begin(); 2664 unsigned char* cp = cstart; 2665 unsigned char* cend = cp + consts_size; 2666 unsigned int bytes_per_line = 4; 2667 unsigned int CP_alignment = 8; 2668 unsigned int n; 2669 2670 st->cr(); 2671 2672 //---< print CP header to make clear what's printed >--- 2673 if( ((uintptr_t)cp&(CP_alignment-1)) == 0 ) { 2674 n = bytes_per_line; 2675 st->print_cr("[Constant Pool]"); 2676 Disassembler::print_location(cp, cstart, cend, st, true, true); 2677 Disassembler::print_hexdata(cp, n, st, true); 2678 st->cr(); 2679 } else { 2680 n = (int)((uintptr_t)cp & (bytes_per_line-1)); 2681 st->print_cr("[Constant Pool (unaligned)]"); 2682 } 2683 2684 //---< print CP contents, bytes_per_line at a time >--- 2685 while (cp < cend) { 2686 Disassembler::print_location(cp, cstart, cend, st, true, false); 2687 Disassembler::print_hexdata(cp, n, st, false); 2688 cp += n; 2689 n = bytes_per_line; 2690 st->cr(); 2691 } 2692 2693 //---< Show potential alignment gap between constant pool and code >--- 2694 cend = code_begin(); 2695 if( cp < cend ) { 2696 n = 4; 2697 st->print_cr("[Code entry alignment]"); 2698 while (cp < cend) { 2699 Disassembler::print_location(cp, cstart, cend, st, false, false); 2700 cp += n; 2701 st->cr(); 2702 } 2703 } 2704 } else { 2705 st->print_cr("[Constant Pool (empty)]"); 2706 } 2707 st->cr(); 2708 } 2709 2710 #endif 2711 2712 // Disassemble this nmethod. 2713 // Print additional debug information, if requested. This could be code 2714 // comments, block comments, profiling counters, etc. 2715 // The undisassembled format is useful no disassembler library is available. 2716 // The resulting hex dump (with markers) can be disassembled later, or on 2717 // another system, when/where a disassembler library is available. 2718 void nmethod::decode2(outputStream* ost) const { 2719 2720 // Called from frame::back_trace_with_decode without ResourceMark. 2721 ResourceMark rm; 2722 2723 // Make sure we have a valid stream to print on. 2724 outputStream* st = ost ? ost : tty; 2725 2726 #if defined(SUPPORT_ABSTRACT_ASSEMBLY) && ! defined(SUPPORT_ASSEMBLY) 2727 const bool use_compressed_format = true; 2728 const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() || 2729 AbstractDisassembler::show_block_comment()); 2730 #else 2731 const bool use_compressed_format = Disassembler::is_abstract(); 2732 const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() || 2733 AbstractDisassembler::show_block_comment()); 2734 #endif 2735 2736 st->cr(); 2737 this->print(st); 2738 st->cr(); 2739 2740 #if defined(SUPPORT_ASSEMBLY) 2741 //---------------------------------- 2742 //---< Print real disassembly >--- 2743 //---------------------------------- 2744 if (! use_compressed_format) { 2745 st->print_cr("[Disassembly]"); 2746 Disassembler::decode(const_cast<nmethod*>(this), st); 2747 st->bol(); 2748 st->print_cr("[/Disassembly]"); 2749 return; 2750 } 2751 #endif 2752 2753 #if defined(SUPPORT_ABSTRACT_ASSEMBLY) 2754 2755 // Compressed undisassembled disassembly format. 2756 // The following status values are defined/supported: 2757 // = 0 - currently at bol() position, nothing printed yet on current line. 2758 // = 1 - currently at position after print_location(). 2759 // > 1 - in the midst of printing instruction stream bytes. 2760 int compressed_format_idx = 0; 2761 int code_comment_column = 0; 2762 const int instr_maxlen = Assembler::instr_maxlen(); 2763 const uint tabspacing = 8; 2764 unsigned char* start = this->code_begin(); 2765 unsigned char* p = this->code_begin(); 2766 unsigned char* end = this->code_end(); 2767 unsigned char* pss = p; // start of a code section (used for offsets) 2768 2769 if ((start == nullptr) || (end == nullptr)) { 2770 st->print_cr("PrintAssembly not possible due to uninitialized section pointers"); 2771 return; 2772 } 2773 #endif 2774 2775 #if defined(SUPPORT_ABSTRACT_ASSEMBLY) 2776 //---< plain abstract disassembly, no comments or anything, just section headers >--- 2777 if (use_compressed_format && ! compressed_with_comments) { 2778 const_cast<nmethod*>(this)->print_constant_pool(st); 2779 2780 //---< Open the output (Marker for post-mortem disassembler) >--- 2781 st->print_cr("[MachCode]"); 2782 const char* header = nullptr; 2783 address p0 = p; 2784 while (p < end) { 2785 address pp = p; 2786 while ((p < end) && (header == nullptr)) { 2787 header = nmethod_section_label(p); 2788 pp = p; 2789 p += Assembler::instr_len(p); 2790 } 2791 if (pp > p0) { 2792 AbstractDisassembler::decode_range_abstract(p0, pp, start, end, st, Assembler::instr_maxlen()); 2793 p0 = pp; 2794 p = pp; 2795 header = nullptr; 2796 } else if (header != nullptr) { 2797 st->bol(); 2798 st->print_cr("%s", header); 2799 header = nullptr; 2800 } 2801 } 2802 //---< Close the output (Marker for post-mortem disassembler) >--- 2803 st->bol(); 2804 st->print_cr("[/MachCode]"); 2805 return; 2806 } 2807 #endif 2808 2809 #if defined(SUPPORT_ABSTRACT_ASSEMBLY) 2810 //---< abstract disassembly with comments and section headers merged in >--- 2811 if (compressed_with_comments) { 2812 const_cast<nmethod*>(this)->print_constant_pool(st); 2813 2814 //---< Open the output (Marker for post-mortem disassembler) >--- 2815 st->print_cr("[MachCode]"); 2816 while ((p < end) && (p != nullptr)) { 2817 const int instruction_size_in_bytes = Assembler::instr_len(p); 2818 2819 //---< Block comments for nmethod. Interrupts instruction stream, if any. >--- 2820 // Outputs a bol() before and a cr() after, but only if a comment is printed. 2821 // Prints nmethod_section_label as well. 2822 if (AbstractDisassembler::show_block_comment()) { 2823 print_block_comment(st, p); 2824 if (st->position() == 0) { 2825 compressed_format_idx = 0; 2826 } 2827 } 2828 2829 //---< New location information after line break >--- 2830 if (compressed_format_idx == 0) { 2831 code_comment_column = Disassembler::print_location(p, pss, end, st, false, false); 2832 compressed_format_idx = 1; 2833 } 2834 2835 //---< Code comment for current instruction. Address range [p..(p+len)) >--- 2836 unsigned char* p_end = p + (ssize_t)instruction_size_in_bytes; 2837 S390_ONLY(if (p_end > end) p_end = end;) // avoid getting past the end 2838 2839 if (AbstractDisassembler::show_comment() && const_cast<nmethod*>(this)->has_code_comment(p, p_end)) { 2840 //---< interrupt instruction byte stream for code comment >--- 2841 if (compressed_format_idx > 1) { 2842 st->cr(); // interrupt byte stream 2843 st->cr(); // add an empty line 2844 code_comment_column = Disassembler::print_location(p, pss, end, st, false, false); 2845 } 2846 const_cast<nmethod*>(this)->print_code_comment_on(st, code_comment_column, p, p_end ); 2847 st->bol(); 2848 compressed_format_idx = 0; 2849 } 2850 2851 //---< New location information after line break >--- 2852 if (compressed_format_idx == 0) { 2853 code_comment_column = Disassembler::print_location(p, pss, end, st, false, false); 2854 compressed_format_idx = 1; 2855 } 2856 2857 //---< Nicely align instructions for readability >--- 2858 if (compressed_format_idx > 1) { 2859 Disassembler::print_delimiter(st); 2860 } 2861 2862 //---< Now, finally, print the actual instruction bytes >--- 2863 unsigned char* p0 = p; 2864 p = Disassembler::decode_instruction_abstract(p, st, instruction_size_in_bytes, instr_maxlen); 2865 compressed_format_idx += (int)(p - p0); 2866 2867 if (Disassembler::start_newline(compressed_format_idx-1)) { 2868 st->cr(); 2869 compressed_format_idx = 0; 2870 } 2871 } 2872 //---< Close the output (Marker for post-mortem disassembler) >--- 2873 st->bol(); 2874 st->print_cr("[/MachCode]"); 2875 return; 2876 } 2877 #endif 2878 } 2879 2880 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY) 2881 2882 const char* nmethod::reloc_string_for(u_char* begin, u_char* end) { 2883 RelocIterator iter(this, begin, end); 2884 bool have_one = false; 2885 while (iter.next()) { 2886 have_one = true; 2887 switch (iter.type()) { 2888 case relocInfo::none: return "no_reloc"; 2889 case relocInfo::oop_type: { 2890 // Get a non-resizable resource-allocated stringStream. 2891 // Our callees make use of (nested) ResourceMarks. 2892 stringStream st(NEW_RESOURCE_ARRAY(char, 1024), 1024); 2893 oop_Relocation* r = iter.oop_reloc(); 2894 oop obj = r->oop_value(); 2895 st.print("oop("); 2896 if (obj == nullptr) st.print("nullptr"); 2897 else obj->print_value_on(&st); 2898 st.print(")"); 2899 return st.as_string(); 2900 } 2901 case relocInfo::metadata_type: { 2902 stringStream st; 2903 metadata_Relocation* r = iter.metadata_reloc(); 2904 Metadata* obj = r->metadata_value(); 2905 st.print("metadata("); 2906 if (obj == nullptr) st.print("nullptr"); 2907 else obj->print_value_on(&st); 2908 st.print(")"); 2909 return st.as_string(); 2910 } 2911 case relocInfo::runtime_call_type: 2912 case relocInfo::runtime_call_w_cp_type: { 2913 stringStream st; 2914 st.print("runtime_call"); 2915 CallRelocation* r = (CallRelocation*)iter.reloc(); 2916 address dest = r->destination(); 2917 CodeBlob* cb = CodeCache::find_blob(dest); 2918 if (cb != nullptr) { 2919 st.print(" %s", cb->name()); 2920 } else { 2921 ResourceMark rm; 2922 const int buflen = 1024; 2923 char* buf = NEW_RESOURCE_ARRAY(char, buflen); 2924 int offset; 2925 if (os::dll_address_to_function_name(dest, buf, buflen, &offset)) { 2926 st.print(" %s", buf); 2927 if (offset != 0) { 2928 st.print("+%d", offset); 2929 } 2930 } 2931 } 2932 return st.as_string(); 2933 } 2934 case relocInfo::virtual_call_type: { 2935 stringStream st; 2936 st.print_raw("virtual_call"); 2937 virtual_call_Relocation* r = iter.virtual_call_reloc(); 2938 Method* m = r->method_value(); 2939 if (m != nullptr) { 2940 assert(m->is_method(), ""); 2941 m->print_short_name(&st); 2942 } 2943 return st.as_string(); 2944 } 2945 case relocInfo::opt_virtual_call_type: { 2946 stringStream st; 2947 st.print_raw("optimized virtual_call"); 2948 opt_virtual_call_Relocation* r = iter.opt_virtual_call_reloc(); 2949 Method* m = r->method_value(); 2950 if (m != nullptr) { 2951 assert(m->is_method(), ""); 2952 m->print_short_name(&st); 2953 } 2954 return st.as_string(); 2955 } 2956 case relocInfo::static_call_type: { 2957 stringStream st; 2958 st.print_raw("static_call"); 2959 static_call_Relocation* r = iter.static_call_reloc(); 2960 Method* m = r->method_value(); 2961 if (m != nullptr) { 2962 assert(m->is_method(), ""); 2963 m->print_short_name(&st); 2964 } 2965 return st.as_string(); 2966 } 2967 case relocInfo::static_stub_type: return "static_stub"; 2968 case relocInfo::external_word_type: return "external_word"; 2969 case relocInfo::internal_word_type: return "internal_word"; 2970 case relocInfo::section_word_type: return "section_word"; 2971 case relocInfo::poll_type: return "poll"; 2972 case relocInfo::poll_return_type: return "poll_return"; 2973 case relocInfo::trampoline_stub_type: return "trampoline_stub"; 2974 case relocInfo::type_mask: return "type_bit_mask"; 2975 2976 default: 2977 break; 2978 } 2979 } 2980 return have_one ? "other" : nullptr; 2981 } 2982 2983 // Return the last scope in (begin..end] 2984 ScopeDesc* nmethod::scope_desc_in(address begin, address end) { 2985 PcDesc* p = pc_desc_near(begin+1); 2986 if (p != nullptr && p->real_pc(this) <= end) { 2987 return new ScopeDesc(this, p); 2988 } 2989 return nullptr; 2990 } 2991 2992 const char* nmethod::nmethod_section_label(address pos) const { 2993 const char* label = nullptr; 2994 if (pos == code_begin()) label = "[Instructions begin]"; 2995 if (pos == entry_point()) label = "[Entry Point]"; 2996 if (pos == inline_entry_point()) label = "[Inline Entry Point]"; 2997 if (pos == verified_entry_point()) label = "[Verified Entry Point]"; 2998 if (pos == verified_inline_entry_point()) label = "[Verified Inline Entry Point]"; 2999 if (pos == verified_inline_ro_entry_point()) label = "[Verified Inline Entry Point (RO)]"; 3000 if (has_method_handle_invokes() && (pos == deopt_mh_handler_begin())) label = "[Deopt MH Handler Code]"; 3001 if (pos == consts_begin() && pos != insts_begin()) label = "[Constants]"; 3002 // Check stub_code before checking exception_handler or deopt_handler. 3003 if (pos == this->stub_begin()) label = "[Stub Code]"; 3004 if (JVMCI_ONLY(_exception_offset >= 0 &&) pos == exception_begin()) label = "[Exception Handler]"; 3005 if (JVMCI_ONLY(_deopt_handler_begin != nullptr &&) pos == deopt_handler_begin()) label = "[Deopt Handler Code]"; 3006 return label; 3007 } 3008 3009 static int maybe_print_entry_label(outputStream* stream, address pos, address entry, const char* label) { 3010 if (pos == entry) { 3011 stream->bol(); 3012 stream->print_cr("%s", label); 3013 return 1; 3014 } else { 3015 return 0; 3016 } 3017 } 3018 3019 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin, bool print_section_labels) const { 3020 if (print_section_labels) { 3021 int n = 0; 3022 // Multiple entry points may be at the same position. Print them all. 3023 n += maybe_print_entry_label(stream, block_begin, entry_point(), "[Entry Point]"); 3024 n += maybe_print_entry_label(stream, block_begin, inline_entry_point(), "[Inline Entry Point]"); 3025 n += maybe_print_entry_label(stream, block_begin, verified_entry_point(), "[Verified Entry Point]"); 3026 n += maybe_print_entry_label(stream, block_begin, verified_inline_entry_point(), "[Verified Inline Entry Point]"); 3027 n += maybe_print_entry_label(stream, block_begin, verified_inline_ro_entry_point(), "[Verified Inline Entry Point (RO)]"); 3028 if (n == 0) { 3029 const char* label = nmethod_section_label(block_begin); 3030 if (label != nullptr) { 3031 stream->bol(); 3032 stream->print_cr("%s", label); 3033 } 3034 } 3035 } 3036 3037 Method* m = method(); 3038 if (m == nullptr || is_osr_method()) { 3039 return; 3040 } 3041 3042 // Print the name of the method (only once) 3043 address low = MIN4(entry_point(), verified_entry_point(), verified_inline_entry_point(), verified_inline_ro_entry_point()); 3044 low = MIN2(low, inline_entry_point()); 3045 assert(low != 0, "sanity"); 3046 if (block_begin == low) { 3047 stream->print(" # "); 3048 m->print_value_on(stream); 3049 stream->cr(); 3050 } 3051 3052 // Print the arguments for the 3 types of verified entry points 3053 CompiledEntrySignature ces(m); 3054 ces.compute_calling_conventions(false); 3055 const GrowableArray<SigEntry>* sig_cc; 3056 const VMRegPair* regs; 3057 if (block_begin == verified_entry_point()) { 3058 sig_cc = ces.sig_cc(); 3059 regs = ces.regs_cc(); 3060 } else if (block_begin == verified_inline_entry_point()) { 3061 sig_cc = ces.sig(); 3062 regs = ces.regs(); 3063 } else if (block_begin == verified_inline_ro_entry_point()) { 3064 sig_cc = ces.sig_cc_ro(); 3065 regs = ces.regs_cc_ro(); 3066 } else { 3067 return; 3068 } 3069 3070 bool has_this = !m->is_static(); 3071 if (ces.has_inline_recv() && block_begin == verified_entry_point()) { 3072 // <this> argument is scalarized for verified_entry_point() 3073 has_this = false; 3074 } 3075 const char* spname = "sp"; // make arch-specific? 3076 int stack_slot_offset = this->frame_size() * wordSize; 3077 int tab1 = 14, tab2 = 24; 3078 int sig_index = 0; 3079 int arg_index = has_this ? -1 : 0; 3080 bool did_old_sp = false; 3081 for (ExtendedSignature sig = ExtendedSignature(sig_cc, SigEntryFilter()); !sig.at_end(); ++sig) { 3082 bool at_this = (arg_index == -1); 3083 bool at_old_sp = false; 3084 BasicType t = (*sig)._bt; 3085 if (at_this) { 3086 stream->print(" # this: "); 3087 } else { 3088 stream->print(" # parm%d: ", arg_index); 3089 } 3090 stream->move_to(tab1); 3091 VMReg fst = regs[sig_index].first(); 3092 VMReg snd = regs[sig_index].second(); 3093 if (fst->is_reg()) { 3094 stream->print("%s", fst->name()); 3095 if (snd->is_valid()) { 3096 stream->print(":%s", snd->name()); 3097 } 3098 } else if (fst->is_stack()) { 3099 int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset; 3100 if (offset == stack_slot_offset) at_old_sp = true; 3101 stream->print("[%s+0x%x]", spname, offset); 3102 } else { 3103 stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd); 3104 } 3105 stream->print(" "); 3106 stream->move_to(tab2); 3107 stream->print("= "); 3108 if (at_this) { 3109 m->method_holder()->print_value_on(stream); 3110 } else { 3111 bool did_name = false; 3112 if (is_reference_type(t)) { 3113 Symbol* name = (*sig)._symbol; 3114 name->print_value_on(stream); 3115 did_name = true; 3116 } 3117 if (!did_name) 3118 stream->print("%s", type2name(t)); 3119 } 3120 if (at_old_sp) { 3121 stream->print(" (%s of caller)", spname); 3122 did_old_sp = true; 3123 } 3124 stream->cr(); 3125 sig_index += type2size[t]; 3126 arg_index += 1; 3127 } 3128 if (!did_old_sp) { 3129 stream->print(" # "); 3130 stream->move_to(tab1); 3131 stream->print("[%s+0x%x]", spname, stack_slot_offset); 3132 stream->print(" (%s of caller)", spname); 3133 stream->cr(); 3134 } 3135 } 3136 3137 // Returns whether this nmethod has code comments. 3138 bool nmethod::has_code_comment(address begin, address end) { 3139 // scopes? 3140 ScopeDesc* sd = scope_desc_in(begin, end); 3141 if (sd != nullptr) return true; 3142 3143 // relocations? 3144 const char* str = reloc_string_for(begin, end); 3145 if (str != nullptr) return true; 3146 3147 // implicit exceptions? 3148 int cont_offset = ImplicitExceptionTable(this).continuation_offset((uint)(begin - code_begin())); 3149 if (cont_offset != 0) return true; 3150 3151 return false; 3152 } 3153 3154 void nmethod::print_code_comment_on(outputStream* st, int column, address begin, address end) { 3155 ImplicitExceptionTable implicit_table(this); 3156 int pc_offset = (int)(begin - code_begin()); 3157 int cont_offset = implicit_table.continuation_offset(pc_offset); 3158 bool oop_map_required = false; 3159 if (cont_offset != 0) { 3160 st->move_to(column, 6, 0); 3161 if (pc_offset == cont_offset) { 3162 st->print("; implicit exception: deoptimizes"); 3163 oop_map_required = true; 3164 } else { 3165 st->print("; implicit exception: dispatches to " INTPTR_FORMAT, p2i(code_begin() + cont_offset)); 3166 } 3167 } 3168 3169 // Find an oopmap in (begin, end]. We use the odd half-closed 3170 // interval so that oop maps and scope descs which are tied to the 3171 // byte after a call are printed with the call itself. OopMaps 3172 // associated with implicit exceptions are printed with the implicit 3173 // instruction. 3174 address base = code_begin(); 3175 ImmutableOopMapSet* oms = oop_maps(); 3176 if (oms != nullptr) { 3177 for (int i = 0, imax = oms->count(); i < imax; i++) { 3178 const ImmutableOopMapPair* pair = oms->pair_at(i); 3179 const ImmutableOopMap* om = pair->get_from(oms); 3180 address pc = base + pair->pc_offset(); 3181 if (pc >= begin) { 3182 #if INCLUDE_JVMCI 3183 bool is_implicit_deopt = implicit_table.continuation_offset(pair->pc_offset()) == (uint) pair->pc_offset(); 3184 #else 3185 bool is_implicit_deopt = false; 3186 #endif 3187 if (is_implicit_deopt ? pc == begin : pc > begin && pc <= end) { 3188 st->move_to(column, 6, 0); 3189 st->print("; "); 3190 om->print_on(st); 3191 oop_map_required = false; 3192 } 3193 } 3194 if (pc > end) { 3195 break; 3196 } 3197 } 3198 } 3199 assert(!oop_map_required, "missed oopmap"); 3200 3201 Thread* thread = Thread::current(); 3202 3203 // Print any debug info present at this pc. 3204 ScopeDesc* sd = scope_desc_in(begin, end); 3205 if (sd != nullptr) { 3206 st->move_to(column, 6, 0); 3207 if (sd->bci() == SynchronizationEntryBCI) { 3208 st->print(";*synchronization entry"); 3209 } else if (sd->bci() == AfterBci) { 3210 st->print(";* method exit (unlocked if synchronized)"); 3211 } else if (sd->bci() == UnwindBci) { 3212 st->print(";* unwind (locked if synchronized)"); 3213 } else if (sd->bci() == AfterExceptionBci) { 3214 st->print(";* unwind (unlocked if synchronized)"); 3215 } else if (sd->bci() == UnknownBci) { 3216 st->print(";* unknown"); 3217 } else if (sd->bci() == InvalidFrameStateBci) { 3218 st->print(";* invalid frame state"); 3219 } else { 3220 if (sd->method() == nullptr) { 3221 st->print("method is nullptr"); 3222 } else if (sd->method()->is_native()) { 3223 st->print("method is native"); 3224 } else { 3225 Bytecodes::Code bc = sd->method()->java_code_at(sd->bci()); 3226 st->print(";*%s", Bytecodes::name(bc)); 3227 switch (bc) { 3228 case Bytecodes::_invokevirtual: 3229 case Bytecodes::_invokespecial: 3230 case Bytecodes::_invokestatic: 3231 case Bytecodes::_invokeinterface: 3232 { 3233 Bytecode_invoke invoke(methodHandle(thread, sd->method()), sd->bci()); 3234 st->print(" "); 3235 if (invoke.name() != nullptr) 3236 invoke.name()->print_symbol_on(st); 3237 else 3238 st->print("<UNKNOWN>"); 3239 break; 3240 } 3241 case Bytecodes::_getfield: 3242 case Bytecodes::_putfield: 3243 case Bytecodes::_getstatic: 3244 case Bytecodes::_putstatic: 3245 { 3246 Bytecode_field field(methodHandle(thread, sd->method()), sd->bci()); 3247 st->print(" "); 3248 if (field.name() != nullptr) 3249 field.name()->print_symbol_on(st); 3250 else 3251 st->print("<UNKNOWN>"); 3252 } 3253 default: 3254 break; 3255 } 3256 } 3257 st->print(" {reexecute=%d rethrow=%d return_oop=%d return_scalarized=%d}", sd->should_reexecute(), sd->rethrow_exception(), sd->return_oop(), sd->return_scalarized()); 3258 } 3259 3260 // Print all scopes 3261 for (;sd != nullptr; sd = sd->sender()) { 3262 st->move_to(column, 6, 0); 3263 st->print("; -"); 3264 if (sd->should_reexecute()) { 3265 st->print(" (reexecute)"); 3266 } 3267 if (sd->method() == nullptr) { 3268 st->print("method is nullptr"); 3269 } else { 3270 sd->method()->print_short_name(st); 3271 } 3272 int lineno = sd->method()->line_number_from_bci(sd->bci()); 3273 if (lineno != -1) { 3274 st->print("@%d (line %d)", sd->bci(), lineno); 3275 } else { 3276 st->print("@%d", sd->bci()); 3277 } 3278 st->cr(); 3279 } 3280 } 3281 3282 // Print relocation information 3283 // Prevent memory leak: allocating without ResourceMark. 3284 ResourceMark rm; 3285 const char* str = reloc_string_for(begin, end); 3286 if (str != nullptr) { 3287 if (sd != nullptr) st->cr(); 3288 st->move_to(column, 6, 0); 3289 st->print("; {%s}", str); 3290 } 3291 } 3292 3293 #endif 3294 3295 address nmethod::call_instruction_address(address pc) const { 3296 if (NativeCall::is_call_before(pc)) { 3297 NativeCall *ncall = nativeCall_before(pc); 3298 return ncall->instruction_address(); 3299 } 3300 return nullptr; 3301 } 3302 3303 #if defined(SUPPORT_DATA_STRUCTS) 3304 void nmethod::print_value_on(outputStream* st) const { 3305 st->print("nmethod"); 3306 print_on(st, nullptr); 3307 } 3308 #endif 3309 3310 #ifndef PRODUCT 3311 3312 void nmethod::print_calls(outputStream* st) { 3313 RelocIterator iter(this); 3314 while (iter.next()) { 3315 switch (iter.type()) { 3316 case relocInfo::virtual_call_type: { 3317 CompiledICLocker ml_verify(this); 3318 CompiledIC_at(&iter)->print(); 3319 break; 3320 } 3321 case relocInfo::static_call_type: 3322 case relocInfo::opt_virtual_call_type: 3323 st->print_cr("Direct call at " INTPTR_FORMAT, p2i(iter.reloc()->addr())); 3324 CompiledDirectCall::at(iter.reloc())->print(); 3325 break; 3326 default: 3327 break; 3328 } 3329 } 3330 } 3331 3332 void nmethod::print_statistics() { 3333 ttyLocker ttyl; 3334 if (xtty != nullptr) xtty->head("statistics type='nmethod'"); 3335 native_nmethod_stats.print_native_nmethod_stats(); 3336 #ifdef COMPILER1 3337 c1_java_nmethod_stats.print_nmethod_stats("C1"); 3338 #endif 3339 #ifdef COMPILER2 3340 c2_java_nmethod_stats.print_nmethod_stats("C2"); 3341 #endif 3342 #if INCLUDE_JVMCI 3343 jvmci_java_nmethod_stats.print_nmethod_stats("JVMCI"); 3344 #endif 3345 unknown_java_nmethod_stats.print_nmethod_stats("Unknown"); 3346 DebugInformationRecorder::print_statistics(); 3347 #ifndef PRODUCT 3348 pc_nmethod_stats.print_pc_stats(); 3349 #endif 3350 Dependencies::print_statistics(); 3351 if (xtty != nullptr) xtty->tail("statistics"); 3352 } 3353 3354 #endif // !PRODUCT 3355 3356 #if INCLUDE_JVMCI 3357 void nmethod::update_speculation(JavaThread* thread) { 3358 jlong speculation = thread->pending_failed_speculation(); 3359 if (speculation != 0) { 3360 guarantee(jvmci_nmethod_data() != nullptr, "failed speculation in nmethod without failed speculation list"); 3361 jvmci_nmethod_data()->add_failed_speculation(this, speculation); 3362 thread->set_pending_failed_speculation(0); 3363 } 3364 } 3365 3366 const char* nmethod::jvmci_name() { 3367 if (jvmci_nmethod_data() != nullptr) { 3368 return jvmci_nmethod_data()->name(); 3369 } 3370 return nullptr; 3371 } 3372 #endif