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