1 /* 2 * Copyright (c) 1997, 2019, 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 "jvm.h" 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/compileBroker.hpp" 36 #include "compiler/compileLog.hpp" 37 #include "compiler/compilerDirectives.hpp" 38 #include "compiler/directivesParser.hpp" 39 #include "compiler/disassembler.hpp" 40 #include "interpreter/bytecode.hpp" 41 #include "logging/log.hpp" 42 #include "logging/logStream.hpp" 43 #include "memory/allocation.inline.hpp" 44 #include "memory/resourceArea.hpp" 45 #include "oops/access.inline.hpp" 46 #include "oops/method.inline.hpp" 47 #include "oops/methodData.hpp" 48 #include "oops/oop.inline.hpp" 49 #include "prims/jvmtiImpl.hpp" 50 #include "runtime/atomic.hpp" 51 #include "runtime/deoptimization.hpp" 52 #include "runtime/flags/flagSetting.hpp" 53 #include "runtime/frame.inline.hpp" 54 #include "runtime/handles.inline.hpp" 55 #include "runtime/jniHandles.inline.hpp" 56 #include "runtime/orderAccess.hpp" 57 #include "runtime/os.hpp" 58 #include "runtime/safepointVerifiers.hpp" 59 #include "runtime/sharedRuntime.hpp" 60 #include "runtime/sweeper.hpp" 61 #include "runtime/vmThread.hpp" 62 #include "utilities/align.hpp" 63 #include "utilities/dtrace.hpp" 64 #include "utilities/events.hpp" 65 #include "utilities/resourceHash.hpp" 66 #include "utilities/xmlstream.hpp" 67 #if INCLUDE_JVMCI 68 #include "jvmci/jvmciRuntime.hpp" 69 #endif 70 71 #ifdef DTRACE_ENABLED 72 73 // Only bother with this argument setup if dtrace is available 74 75 #define DTRACE_METHOD_UNLOAD_PROBE(method) \ 76 { \ 77 Method* m = (method); \ 78 if (m != NULL) { \ 79 Symbol* klass_name = m->klass_name(); \ 80 Symbol* name = m->name(); \ 81 Symbol* signature = m->signature(); \ 82 HOTSPOT_COMPILED_METHOD_UNLOAD( \ 83 (char *) klass_name->bytes(), klass_name->utf8_length(), \ 84 (char *) name->bytes(), name->utf8_length(), \ 85 (char *) signature->bytes(), signature->utf8_length()); \ 86 } \ 87 } 88 89 #else // ndef DTRACE_ENABLED 90 91 #define DTRACE_METHOD_UNLOAD_PROBE(method) 92 93 #endif 94 95 //--------------------------------------------------------------------------------- 96 // NMethod statistics 97 // They are printed under various flags, including: 98 // PrintC1Statistics, PrintOptoStatistics, LogVMOutput, and LogCompilation. 99 // (In the latter two cases, they like other stats are printed to the log only.) 100 101 #ifndef PRODUCT 102 // These variables are put into one block to reduce relocations 103 // and make it simpler to print from the debugger. 104 struct java_nmethod_stats_struct { 105 int nmethod_count; 106 int total_size; 107 int relocation_size; 108 int consts_size; 109 int insts_size; 110 int stub_size; 111 int scopes_data_size; 112 int scopes_pcs_size; 113 int dependencies_size; 114 int handler_table_size; 115 int nul_chk_table_size; 116 #if INCLUDE_JVMCI 117 int speculations_size; 118 int jvmci_data_size; 119 #endif 120 int oops_size; 121 int metadata_size; 122 123 void note_nmethod(nmethod* nm) { 124 nmethod_count += 1; 125 total_size += nm->size(); 126 relocation_size += nm->relocation_size(); 127 consts_size += nm->consts_size(); 128 insts_size += nm->insts_size(); 129 stub_size += nm->stub_size(); 130 oops_size += nm->oops_size(); 131 metadata_size += nm->metadata_size(); 132 scopes_data_size += nm->scopes_data_size(); 133 scopes_pcs_size += nm->scopes_pcs_size(); 134 dependencies_size += nm->dependencies_size(); 135 handler_table_size += nm->handler_table_size(); 136 nul_chk_table_size += nm->nul_chk_table_size(); 137 #if INCLUDE_JVMCI 138 speculations_size += nm->speculations_size(); 139 jvmci_data_size += nm->jvmci_data_size(); 140 #endif 141 } 142 void print_nmethod_stats(const char* name) { 143 if (nmethod_count == 0) return; 144 tty->print_cr("Statistics for %d bytecoded nmethods for %s:", nmethod_count, name); 145 if (total_size != 0) tty->print_cr(" total in heap = %d", total_size); 146 if (nmethod_count != 0) tty->print_cr(" header = " SIZE_FORMAT, nmethod_count * sizeof(nmethod)); 147 if (relocation_size != 0) tty->print_cr(" relocation = %d", relocation_size); 148 if (consts_size != 0) tty->print_cr(" constants = %d", consts_size); 149 if (insts_size != 0) tty->print_cr(" main code = %d", insts_size); 150 if (stub_size != 0) tty->print_cr(" stub code = %d", stub_size); 151 if (oops_size != 0) tty->print_cr(" oops = %d", oops_size); 152 if (metadata_size != 0) tty->print_cr(" metadata = %d", metadata_size); 153 if (scopes_data_size != 0) tty->print_cr(" scopes data = %d", scopes_data_size); 154 if (scopes_pcs_size != 0) tty->print_cr(" scopes pcs = %d", scopes_pcs_size); 155 if (dependencies_size != 0) tty->print_cr(" dependencies = %d", dependencies_size); 156 if (handler_table_size != 0) tty->print_cr(" handler table = %d", handler_table_size); 157 if (nul_chk_table_size != 0) tty->print_cr(" nul chk table = %d", nul_chk_table_size); 158 #if INCLUDE_JVMCI 159 if (speculations_size != 0) tty->print_cr(" speculations = %d", speculations_size); 160 if (jvmci_data_size != 0) tty->print_cr(" JVMCI data = %d", jvmci_data_size); 161 #endif 162 } 163 }; 164 165 struct native_nmethod_stats_struct { 166 int native_nmethod_count; 167 int native_total_size; 168 int native_relocation_size; 169 int native_insts_size; 170 int native_oops_size; 171 int native_metadata_size; 172 void note_native_nmethod(nmethod* nm) { 173 native_nmethod_count += 1; 174 native_total_size += nm->size(); 175 native_relocation_size += nm->relocation_size(); 176 native_insts_size += nm->insts_size(); 177 native_oops_size += nm->oops_size(); 178 native_metadata_size += nm->metadata_size(); 179 } 180 void print_native_nmethod_stats() { 181 if (native_nmethod_count == 0) return; 182 tty->print_cr("Statistics for %d native nmethods:", native_nmethod_count); 183 if (native_total_size != 0) tty->print_cr(" N. total size = %d", native_total_size); 184 if (native_relocation_size != 0) tty->print_cr(" N. relocation = %d", native_relocation_size); 185 if (native_insts_size != 0) tty->print_cr(" N. main code = %d", native_insts_size); 186 if (native_oops_size != 0) tty->print_cr(" N. oops = %d", native_oops_size); 187 if (native_metadata_size != 0) tty->print_cr(" N. metadata = %d", native_metadata_size); 188 } 189 }; 190 191 struct pc_nmethod_stats_struct { 192 int pc_desc_resets; // number of resets (= number of caches) 193 int pc_desc_queries; // queries to nmethod::find_pc_desc 194 int pc_desc_approx; // number of those which have approximate true 195 int pc_desc_repeats; // number of _pc_descs[0] hits 196 int pc_desc_hits; // number of LRU cache hits 197 int pc_desc_tests; // total number of PcDesc examinations 198 int pc_desc_searches; // total number of quasi-binary search steps 199 int pc_desc_adds; // number of LUR cache insertions 200 201 void print_pc_stats() { 202 tty->print_cr("PcDesc Statistics: %d queries, %.2f comparisons per query", 203 pc_desc_queries, 204 (double)(pc_desc_tests + pc_desc_searches) 205 / pc_desc_queries); 206 tty->print_cr(" caches=%d queries=%d/%d, hits=%d+%d, tests=%d+%d, adds=%d", 207 pc_desc_resets, 208 pc_desc_queries, pc_desc_approx, 209 pc_desc_repeats, pc_desc_hits, 210 pc_desc_tests, pc_desc_searches, pc_desc_adds); 211 } 212 }; 213 214 #ifdef COMPILER1 215 static java_nmethod_stats_struct c1_java_nmethod_stats; 216 #endif 217 #ifdef COMPILER2 218 static java_nmethod_stats_struct c2_java_nmethod_stats; 219 #endif 220 #if INCLUDE_JVMCI 221 static java_nmethod_stats_struct jvmci_java_nmethod_stats; 222 #endif 223 static java_nmethod_stats_struct unknown_java_nmethod_stats; 224 225 static native_nmethod_stats_struct native_nmethod_stats; 226 static pc_nmethod_stats_struct pc_nmethod_stats; 227 228 static void note_java_nmethod(nmethod* nm) { 229 #ifdef COMPILER1 230 if (nm->is_compiled_by_c1()) { 231 c1_java_nmethod_stats.note_nmethod(nm); 232 } else 233 #endif 234 #ifdef COMPILER2 235 if (nm->is_compiled_by_c2()) { 236 c2_java_nmethod_stats.note_nmethod(nm); 237 } else 238 #endif 239 #if INCLUDE_JVMCI 240 if (nm->is_compiled_by_jvmci()) { 241 jvmci_java_nmethod_stats.note_nmethod(nm); 242 } else 243 #endif 244 { 245 unknown_java_nmethod_stats.note_nmethod(nm); 246 } 247 } 248 #endif // !PRODUCT 249 250 //--------------------------------------------------------------------------------- 251 252 253 ExceptionCache::ExceptionCache(Handle exception, address pc, address handler) { 254 assert(pc != NULL, "Must be non null"); 255 assert(exception.not_null(), "Must be non null"); 256 assert(handler != NULL, "Must be non null"); 257 258 _count = 0; 259 _exception_type = exception->klass(); 260 _next = NULL; 261 _purge_list_next = NULL; 262 263 add_address_and_handler(pc,handler); 264 } 265 266 267 address ExceptionCache::match(Handle exception, address pc) { 268 assert(pc != NULL,"Must be non null"); 269 assert(exception.not_null(),"Must be non null"); 270 if (exception->klass() == exception_type()) { 271 return (test_address(pc)); 272 } 273 274 return NULL; 275 } 276 277 278 bool ExceptionCache::match_exception_with_space(Handle exception) { 279 assert(exception.not_null(),"Must be non null"); 280 if (exception->klass() == exception_type() && count() < cache_size) { 281 return true; 282 } 283 return false; 284 } 285 286 287 address ExceptionCache::test_address(address addr) { 288 int limit = count(); 289 for (int i = 0; i < limit; i++) { 290 if (pc_at(i) == addr) { 291 return handler_at(i); 292 } 293 } 294 return NULL; 295 } 296 297 298 bool ExceptionCache::add_address_and_handler(address addr, address handler) { 299 if (test_address(addr) == handler) return true; 300 301 int index = count(); 302 if (index < cache_size) { 303 set_pc_at(index, addr); 304 set_handler_at(index, handler); 305 increment_count(); 306 return true; 307 } 308 return false; 309 } 310 311 ExceptionCache* ExceptionCache::next() { 312 return Atomic::load(&_next); 313 } 314 315 void ExceptionCache::set_next(ExceptionCache *ec) { 316 Atomic::store(ec, &_next); 317 } 318 319 //----------------------------------------------------------------------------- 320 321 322 // Helper used by both find_pc_desc methods. 323 static inline bool match_desc(PcDesc* pc, int pc_offset, bool approximate) { 324 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_tests); 325 if (!approximate) 326 return pc->pc_offset() == pc_offset; 327 else 328 return (pc-1)->pc_offset() < pc_offset && pc_offset <= pc->pc_offset(); 329 } 330 331 void PcDescCache::reset_to(PcDesc* initial_pc_desc) { 332 if (initial_pc_desc == NULL) { 333 _pc_descs[0] = NULL; // native method; no PcDescs at all 334 return; 335 } 336 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_resets); 337 // reset the cache by filling it with benign (non-null) values 338 assert(initial_pc_desc->pc_offset() < 0, "must be sentinel"); 339 for (int i = 0; i < cache_size; i++) 340 _pc_descs[i] = initial_pc_desc; 341 } 342 343 PcDesc* PcDescCache::find_pc_desc(int pc_offset, bool approximate) { 344 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_queries); 345 NOT_PRODUCT(if (approximate) ++pc_nmethod_stats.pc_desc_approx); 346 347 // Note: one might think that caching the most recently 348 // read value separately would be a win, but one would be 349 // wrong. When many threads are updating it, the cache 350 // line it's in would bounce between caches, negating 351 // any benefit. 352 353 // In order to prevent race conditions do not load cache elements 354 // repeatedly, but use a local copy: 355 PcDesc* res; 356 357 // Step one: Check the most recently added value. 358 res = _pc_descs[0]; 359 if (res == NULL) return NULL; // native method; no PcDescs at all 360 if (match_desc(res, pc_offset, approximate)) { 361 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_repeats); 362 return res; 363 } 364 365 // Step two: Check the rest of the LRU cache. 366 for (int i = 1; i < cache_size; ++i) { 367 res = _pc_descs[i]; 368 if (res->pc_offset() < 0) break; // optimization: skip empty cache 369 if (match_desc(res, pc_offset, approximate)) { 370 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_hits); 371 return res; 372 } 373 } 374 375 // Report failure. 376 return NULL; 377 } 378 379 void PcDescCache::add_pc_desc(PcDesc* pc_desc) { 380 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_adds); 381 // Update the LRU cache by shifting pc_desc forward. 382 for (int i = 0; i < cache_size; i++) { 383 PcDesc* next = _pc_descs[i]; 384 _pc_descs[i] = pc_desc; 385 pc_desc = next; 386 } 387 } 388 389 // adjust pcs_size so that it is a multiple of both oopSize and 390 // sizeof(PcDesc) (assumes that if sizeof(PcDesc) is not a multiple 391 // of oopSize, then 2*sizeof(PcDesc) is) 392 static int adjust_pcs_size(int pcs_size) { 393 int nsize = align_up(pcs_size, oopSize); 394 if ((nsize % sizeof(PcDesc)) != 0) { 395 nsize = pcs_size + sizeof(PcDesc); 396 } 397 assert((nsize % oopSize) == 0, "correct alignment"); 398 return nsize; 399 } 400 401 402 int nmethod::total_size() const { 403 return 404 consts_size() + 405 insts_size() + 406 stub_size() + 407 scopes_data_size() + 408 scopes_pcs_size() + 409 handler_table_size() + 410 nul_chk_table_size(); 411 } 412 413 address* nmethod::orig_pc_addr(const frame* fr) { 414 return (address*) ((address)fr->unextended_sp() + _orig_pc_offset); 415 } 416 417 const char* nmethod::compile_kind() const { 418 if (is_osr_method()) return "osr"; 419 if (method() != NULL && is_native_method()) return "c2n"; 420 return NULL; 421 } 422 423 // Fill in default values for various flag fields 424 void nmethod::init_defaults() { 425 _state = not_installed; 426 _has_flushed_dependencies = 0; 427 _lock_count = 0; 428 _stack_traversal_mark = 0; 429 _unload_reported = false; // jvmti state 430 _is_far_code = false; // nmethods are located in CodeCache 431 432 #ifdef ASSERT 433 _oops_are_stale = false; 434 #endif 435 436 _oops_do_mark_link = NULL; 437 _jmethod_id = NULL; 438 _osr_link = NULL; 439 #if INCLUDE_RTM_OPT 440 _rtm_state = NoRTM; 441 #endif 442 } 443 444 nmethod* nmethod::new_native_nmethod(const methodHandle& method, 445 int compile_id, 446 CodeBuffer *code_buffer, 447 int vep_offset, 448 int frame_complete, 449 int frame_size, 450 ByteSize basic_lock_owner_sp_offset, 451 ByteSize basic_lock_sp_offset, 452 OopMapSet* oop_maps) { 453 code_buffer->finalize_oop_references(method); 454 // create nmethod 455 nmethod* nm = NULL; 456 { 457 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 458 int native_nmethod_size = CodeBlob::allocation_size(code_buffer, sizeof(nmethod)); 459 CodeOffsets offsets; 460 offsets.set_value(CodeOffsets::Verified_Entry, vep_offset); 461 offsets.set_value(CodeOffsets::Frame_Complete, frame_complete); 462 nm = new (native_nmethod_size, CompLevel_none) nmethod(method(), compiler_none, native_nmethod_size, 463 compile_id, &offsets, 464 code_buffer, frame_size, 465 basic_lock_owner_sp_offset, 466 basic_lock_sp_offset, oop_maps); 467 NOT_PRODUCT(if (nm != NULL) native_nmethod_stats.note_native_nmethod(nm)); 468 } 469 470 if (nm != NULL) { 471 // verify nmethod 472 debug_only(nm->verify();) // might block 473 474 nm->log_new_nmethod(); 475 nm->make_in_use(); 476 } 477 return nm; 478 } 479 480 nmethod* nmethod::new_nmethod(const methodHandle& method, 481 int compile_id, 482 int entry_bci, 483 CodeOffsets* offsets, 484 int orig_pc_offset, 485 DebugInformationRecorder* debug_info, 486 Dependencies* dependencies, 487 CodeBuffer* code_buffer, int frame_size, 488 OopMapSet* oop_maps, 489 ExceptionHandlerTable* handler_table, 490 ImplicitExceptionTable* nul_chk_table, 491 AbstractCompiler* compiler, 492 int comp_level 493 #if INCLUDE_JVMCI 494 , char* speculations, 495 int speculations_len, 496 int nmethod_mirror_index, 497 const char* nmethod_mirror_name, 498 FailedSpeculation** failed_speculations 499 #endif 500 ) 501 { 502 assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR"); 503 code_buffer->finalize_oop_references(method); 504 // create nmethod 505 nmethod* nm = NULL; 506 { MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 507 #if INCLUDE_JVMCI 508 int jvmci_data_size = !compiler->is_jvmci() ? 0 : JVMCINMethodData::compute_size(nmethod_mirror_name); 509 #endif 510 int nmethod_size = 511 CodeBlob::allocation_size(code_buffer, sizeof(nmethod)) 512 + adjust_pcs_size(debug_info->pcs_size()) 513 + align_up((int)dependencies->size_in_bytes(), oopSize) 514 + align_up(handler_table->size_in_bytes() , oopSize) 515 + align_up(nul_chk_table->size_in_bytes() , oopSize) 516 #if INCLUDE_JVMCI 517 + align_up(speculations_len , oopSize) 518 + align_up(jvmci_data_size , oopSize) 519 #endif 520 + align_up(debug_info->data_size() , oopSize); 521 522 nm = new (nmethod_size, comp_level) 523 nmethod(method(), compiler->type(), nmethod_size, compile_id, entry_bci, offsets, 524 orig_pc_offset, debug_info, dependencies, code_buffer, frame_size, 525 oop_maps, 526 handler_table, 527 nul_chk_table, 528 compiler, 529 comp_level 530 #if INCLUDE_JVMCI 531 , speculations, 532 speculations_len, 533 jvmci_data_size 534 #endif 535 ); 536 537 if (nm != NULL) { 538 #if INCLUDE_JVMCI 539 if (compiler->is_jvmci()) { 540 // Initialize the JVMCINMethodData object inlined into nm 541 nm->jvmci_nmethod_data()->initialize(nmethod_mirror_index, nmethod_mirror_name, failed_speculations); 542 } 543 #endif 544 // To make dependency checking during class loading fast, record 545 // the nmethod dependencies in the classes it is dependent on. 546 // This allows the dependency checking code to simply walk the 547 // class hierarchy above the loaded class, checking only nmethods 548 // which are dependent on those classes. The slow way is to 549 // check every nmethod for dependencies which makes it linear in 550 // the number of methods compiled. For applications with a lot 551 // classes the slow way is too slow. 552 for (Dependencies::DepStream deps(nm); deps.next(); ) { 553 if (deps.type() == Dependencies::call_site_target_value) { 554 // CallSite dependencies are managed on per-CallSite instance basis. 555 oop call_site = deps.argument_oop(0); 556 MethodHandles::add_dependent_nmethod(call_site, nm); 557 } else { 558 Klass* klass = deps.context_type(); 559 if (klass == NULL) { 560 continue; // ignore things like evol_method 561 } 562 // record this nmethod as dependent on this klass 563 InstanceKlass::cast(klass)->add_dependent_nmethod(nm); 564 } 565 } 566 NOT_PRODUCT(if (nm != NULL) note_java_nmethod(nm)); 567 } 568 } 569 // Do verification and logging outside CodeCache_lock. 570 if (nm != NULL) { 571 // Safepoints in nmethod::verify aren't allowed because nm hasn't been installed yet. 572 DEBUG_ONLY(nm->verify();) 573 nm->log_new_nmethod(); 574 } 575 return nm; 576 } 577 578 // For native wrappers 579 nmethod::nmethod( 580 Method* method, 581 CompilerType type, 582 int nmethod_size, 583 int compile_id, 584 CodeOffsets* offsets, 585 CodeBuffer* code_buffer, 586 int frame_size, 587 ByteSize basic_lock_owner_sp_offset, 588 ByteSize basic_lock_sp_offset, 589 OopMapSet* oop_maps ) 590 : CompiledMethod(method, "native nmethod", type, nmethod_size, sizeof(nmethod), code_buffer, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps, false), 591 _is_unloading_state(0), 592 _native_receiver_sp_offset(basic_lock_owner_sp_offset), 593 _native_basic_lock_sp_offset(basic_lock_sp_offset) 594 { 595 { 596 int scopes_data_offset = 0; 597 int deoptimize_offset = 0; 598 int deoptimize_mh_offset = 0; 599 600 debug_only(NoSafepointVerifier nsv;) 601 assert_locked_or_safepoint(CodeCache_lock); 602 603 init_defaults(); 604 _entry_bci = InvocationEntryBci; 605 // We have no exception handler or deopt handler make the 606 // values something that will never match a pc like the nmethod vtable entry 607 _exception_offset = 0; 608 _orig_pc_offset = 0; 609 610 _consts_offset = data_offset(); 611 _stub_offset = data_offset(); 612 _oops_offset = data_offset(); 613 _metadata_offset = _oops_offset + align_up(code_buffer->total_oop_size(), oopSize); 614 scopes_data_offset = _metadata_offset + align_up(code_buffer->total_metadata_size(), wordSize); 615 _scopes_pcs_offset = scopes_data_offset; 616 _dependencies_offset = _scopes_pcs_offset; 617 _handler_table_offset = _dependencies_offset; 618 _nul_chk_table_offset = _handler_table_offset; 619 #if INCLUDE_JVMCI 620 _speculations_offset = _nul_chk_table_offset; 621 _jvmci_data_offset = _speculations_offset; 622 _nmethod_end_offset = _jvmci_data_offset; 623 #else 624 _nmethod_end_offset = _nul_chk_table_offset; 625 #endif 626 _compile_id = compile_id; 627 _comp_level = CompLevel_none; 628 _entry_point = code_begin() + offsets->value(CodeOffsets::Entry); 629 _verified_entry_point = code_begin() + offsets->value(CodeOffsets::Verified_Entry); 630 _osr_entry_point = NULL; 631 _exception_cache = NULL; 632 _pc_desc_container.reset_to(NULL); 633 _hotness_counter = NMethodSweeper::hotness_counter_reset_val(); 634 635 _scopes_data_begin = (address) this + scopes_data_offset; 636 _deopt_handler_begin = (address) this + deoptimize_offset; 637 _deopt_mh_handler_begin = (address) this + deoptimize_mh_offset; 638 639 code_buffer->copy_code_and_locs_to(this); 640 code_buffer->copy_values_to(this); 641 642 clear_unloading_state(); 643 644 Universe::heap()->register_nmethod(this); 645 debug_only(Universe::heap()->verify_nmethod(this)); 646 647 CodeCache::commit(this); 648 } 649 650 if (PrintNativeNMethods || PrintDebugInfo || PrintRelocations || PrintDependencies) { 651 ttyLocker ttyl; // keep the following output all in one block 652 // This output goes directly to the tty, not the compiler log. 653 // To enable tools to match it up with the compilation activity, 654 // be sure to tag this tty output with the compile ID. 655 if (xtty != NULL) { 656 xtty->begin_head("print_native_nmethod"); 657 xtty->method(_method); 658 xtty->stamp(); 659 xtty->end_head(" address='" INTPTR_FORMAT "'", (intptr_t) this); 660 } 661 // print the header part first 662 print(); 663 // then print the requested information 664 if (PrintNativeNMethods) { 665 print_code(); 666 if (oop_maps != NULL) { 667 oop_maps->print(); 668 } 669 } 670 if (PrintRelocations) { 671 print_relocations(); 672 } 673 if (xtty != NULL) { 674 xtty->tail("print_native_nmethod"); 675 } 676 } 677 } 678 679 void* nmethod::operator new(size_t size, int nmethod_size, int comp_level) throw () { 680 return CodeCache::allocate(nmethod_size, CodeCache::get_code_blob_type(comp_level)); 681 } 682 683 nmethod::nmethod( 684 Method* method, 685 CompilerType type, 686 int nmethod_size, 687 int compile_id, 688 int entry_bci, 689 CodeOffsets* offsets, 690 int orig_pc_offset, 691 DebugInformationRecorder* debug_info, 692 Dependencies* dependencies, 693 CodeBuffer *code_buffer, 694 int frame_size, 695 OopMapSet* oop_maps, 696 ExceptionHandlerTable* handler_table, 697 ImplicitExceptionTable* nul_chk_table, 698 AbstractCompiler* compiler, 699 int comp_level 700 #if INCLUDE_JVMCI 701 , char* speculations, 702 int speculations_len, 703 int jvmci_data_size 704 #endif 705 ) 706 : CompiledMethod(method, "nmethod", type, nmethod_size, sizeof(nmethod), code_buffer, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps, false), 707 _is_unloading_state(0), 708 _native_receiver_sp_offset(in_ByteSize(-1)), 709 _native_basic_lock_sp_offset(in_ByteSize(-1)) 710 { 711 assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR"); 712 { 713 debug_only(NoSafepointVerifier nsv;) 714 assert_locked_or_safepoint(CodeCache_lock); 715 716 _deopt_handler_begin = (address) this; 717 _deopt_mh_handler_begin = (address) this; 718 719 init_defaults(); 720 _entry_bci = entry_bci; 721 _compile_id = compile_id; 722 _comp_level = comp_level; 723 _orig_pc_offset = orig_pc_offset; 724 _hotness_counter = NMethodSweeper::hotness_counter_reset_val(); 725 726 // Section offsets 727 _consts_offset = content_offset() + code_buffer->total_offset_of(code_buffer->consts()); 728 _stub_offset = content_offset() + code_buffer->total_offset_of(code_buffer->stubs()); 729 set_ctable_begin(header_begin() + _consts_offset); 730 731 #if INCLUDE_JVMCI 732 if (compiler->is_jvmci()) { 733 // JVMCI might not produce any stub sections 734 if (offsets->value(CodeOffsets::Exceptions) != -1) { 735 _exception_offset = code_offset() + offsets->value(CodeOffsets::Exceptions); 736 } else { 737 _exception_offset = -1; 738 } 739 if (offsets->value(CodeOffsets::Deopt) != -1) { 740 _deopt_handler_begin = (address) this + code_offset() + offsets->value(CodeOffsets::Deopt); 741 } else { 742 _deopt_handler_begin = NULL; 743 } 744 if (offsets->value(CodeOffsets::DeoptMH) != -1) { 745 _deopt_mh_handler_begin = (address) this + code_offset() + offsets->value(CodeOffsets::DeoptMH); 746 } else { 747 _deopt_mh_handler_begin = NULL; 748 } 749 } else { 750 #endif 751 // Exception handler and deopt handler are in the stub section 752 assert(offsets->value(CodeOffsets::Exceptions) != -1, "must be set"); 753 assert(offsets->value(CodeOffsets::Deopt ) != -1, "must be set"); 754 755 _exception_offset = _stub_offset + offsets->value(CodeOffsets::Exceptions); 756 _deopt_handler_begin = (address) this + _stub_offset + offsets->value(CodeOffsets::Deopt); 757 if (offsets->value(CodeOffsets::DeoptMH) != -1) { 758 _deopt_mh_handler_begin = (address) this + _stub_offset + offsets->value(CodeOffsets::DeoptMH); 759 } else { 760 _deopt_mh_handler_begin = NULL; 761 } 762 #if INCLUDE_JVMCI 763 } 764 #endif 765 if (offsets->value(CodeOffsets::UnwindHandler) != -1) { 766 _unwind_handler_offset = code_offset() + offsets->value(CodeOffsets::UnwindHandler); 767 } else { 768 _unwind_handler_offset = -1; 769 } 770 771 _oops_offset = data_offset(); 772 _metadata_offset = _oops_offset + align_up(code_buffer->total_oop_size(), oopSize); 773 int scopes_data_offset = _metadata_offset + align_up(code_buffer->total_metadata_size(), wordSize); 774 775 _scopes_pcs_offset = scopes_data_offset + align_up(debug_info->data_size (), oopSize); 776 _dependencies_offset = _scopes_pcs_offset + adjust_pcs_size(debug_info->pcs_size()); 777 _handler_table_offset = _dependencies_offset + align_up((int)dependencies->size_in_bytes (), oopSize); 778 _nul_chk_table_offset = _handler_table_offset + align_up(handler_table->size_in_bytes(), oopSize); 779 #if INCLUDE_JVMCI 780 _speculations_offset = _nul_chk_table_offset + align_up(nul_chk_table->size_in_bytes(), oopSize); 781 _jvmci_data_offset = _speculations_offset + align_up(speculations_len, oopSize); 782 _nmethod_end_offset = _jvmci_data_offset + align_up(jvmci_data_size, oopSize); 783 #else 784 _nmethod_end_offset = _nul_chk_table_offset + align_up(nul_chk_table->size_in_bytes(), oopSize); 785 #endif 786 _entry_point = code_begin() + offsets->value(CodeOffsets::Entry); 787 _verified_entry_point = code_begin() + offsets->value(CodeOffsets::Verified_Entry); 788 _osr_entry_point = code_begin() + offsets->value(CodeOffsets::OSR_Entry); 789 _exception_cache = NULL; 790 791 _scopes_data_begin = (address) this + scopes_data_offset; 792 793 _pc_desc_container.reset_to(scopes_pcs_begin()); 794 795 code_buffer->copy_code_and_locs_to(this); 796 // Copy contents of ScopeDescRecorder to nmethod 797 code_buffer->copy_values_to(this); 798 debug_info->copy_to(this); 799 dependencies->copy_to(this); 800 clear_unloading_state(); 801 802 Universe::heap()->register_nmethod(this); 803 debug_only(Universe::heap()->verify_nmethod(this)); 804 805 CodeCache::commit(this); 806 807 // Copy contents of ExceptionHandlerTable to nmethod 808 handler_table->copy_to(this); 809 nul_chk_table->copy_to(this); 810 811 #if INCLUDE_JVMCI 812 // Copy speculations to nmethod 813 if (speculations_size() != 0) { 814 memcpy(speculations_begin(), speculations, speculations_len); 815 } 816 #endif 817 818 // we use the information of entry points to find out if a method is 819 // static or non static 820 assert(compiler->is_c2() || compiler->is_jvmci() || 821 _method->is_static() == (entry_point() == _verified_entry_point), 822 " entry points must be same for static methods and vice versa"); 823 } 824 } 825 826 // Print a short set of xml attributes to identify this nmethod. The 827 // output should be embedded in some other element. 828 void nmethod::log_identity(xmlStream* log) const { 829 log->print(" compile_id='%d'", compile_id()); 830 const char* nm_kind = compile_kind(); 831 if (nm_kind != NULL) log->print(" compile_kind='%s'", nm_kind); 832 log->print(" compiler='%s'", compiler_name()); 833 if (TieredCompilation) { 834 log->print(" level='%d'", comp_level()); 835 } 836 #if INCLUDE_JVMCI 837 if (jvmci_nmethod_data() != NULL) { 838 const char* jvmci_name = jvmci_nmethod_data()->name(); 839 if (jvmci_name != NULL) { 840 log->print(" jvmci_mirror_name='"); 841 log->text("%s", jvmci_name); 842 log->print("'"); 843 } 844 } 845 #endif 846 } 847 848 849 #define LOG_OFFSET(log, name) \ 850 if (p2i(name##_end()) - p2i(name##_begin())) \ 851 log->print(" " XSTR(name) "_offset='" INTX_FORMAT "'" , \ 852 p2i(name##_begin()) - p2i(this)) 853 854 855 void nmethod::log_new_nmethod() const { 856 if (LogCompilation && xtty != NULL) { 857 ttyLocker ttyl; 858 HandleMark hm; 859 xtty->begin_elem("nmethod"); 860 log_identity(xtty); 861 xtty->print(" entry='" INTPTR_FORMAT "' size='%d'", p2i(code_begin()), size()); 862 xtty->print(" address='" INTPTR_FORMAT "'", p2i(this)); 863 864 LOG_OFFSET(xtty, relocation); 865 LOG_OFFSET(xtty, consts); 866 LOG_OFFSET(xtty, insts); 867 LOG_OFFSET(xtty, stub); 868 LOG_OFFSET(xtty, scopes_data); 869 LOG_OFFSET(xtty, scopes_pcs); 870 LOG_OFFSET(xtty, dependencies); 871 LOG_OFFSET(xtty, handler_table); 872 LOG_OFFSET(xtty, nul_chk_table); 873 LOG_OFFSET(xtty, oops); 874 LOG_OFFSET(xtty, metadata); 875 876 xtty->method(method()); 877 xtty->stamp(); 878 xtty->end_elem(); 879 } 880 } 881 882 #undef LOG_OFFSET 883 884 885 // Print out more verbose output usually for a newly created nmethod. 886 void nmethod::print_on(outputStream* st, const char* msg) const { 887 if (st != NULL) { 888 ttyLocker ttyl; 889 if (WizardMode) { 890 CompileTask::print(st, this, msg, /*short_form:*/ true); 891 st->print_cr(" (" INTPTR_FORMAT ")", p2i(this)); 892 } else { 893 CompileTask::print(st, this, msg, /*short_form:*/ false); 894 } 895 } 896 } 897 898 void nmethod::maybe_print_nmethod(DirectiveSet* directive) { 899 bool printnmethods = directive->PrintAssemblyOption || directive->PrintNMethodsOption; 900 if (printnmethods || PrintDebugInfo || PrintRelocations || PrintDependencies || PrintExceptionHandlers) { 901 print_nmethod(printnmethods); 902 } 903 } 904 905 void nmethod::print_nmethod(bool printmethod) { 906 ttyLocker ttyl; // keep the following output all in one block 907 if (xtty != NULL) { 908 xtty->begin_head("print_nmethod"); 909 xtty->stamp(); 910 xtty->end_head(); 911 } 912 // print the header part first 913 print(); 914 // then print the requested information 915 if (printmethod) { 916 print_code(); 917 print_pcs(); 918 if (oop_maps()) { 919 oop_maps()->print(); 920 } 921 } 922 if (printmethod || PrintDebugInfo || CompilerOracle::has_option_string(_method, "PrintDebugInfo")) { 923 print_scopes(); 924 } 925 if (printmethod || PrintRelocations || CompilerOracle::has_option_string(_method, "PrintRelocations")) { 926 print_relocations(); 927 } 928 if (printmethod || PrintDependencies || CompilerOracle::has_option_string(_method, "PrintDependencies")) { 929 print_dependencies(); 930 } 931 if (printmethod || PrintExceptionHandlers) { 932 print_handler_table(); 933 print_nul_chk_table(); 934 } 935 if (printmethod) { 936 print_recorded_oops(); 937 print_recorded_metadata(); 938 } 939 if (xtty != NULL) { 940 xtty->tail("print_nmethod"); 941 } 942 } 943 944 945 // Promote one word from an assembly-time handle to a live embedded oop. 946 inline void nmethod::initialize_immediate_oop(oop* dest, jobject handle) { 947 if (handle == NULL || 948 // As a special case, IC oops are initialized to 1 or -1. 949 handle == (jobject) Universe::non_oop_word()) { 950 (*dest) = (oop) handle; 951 } else { 952 (*dest) = JNIHandles::resolve_non_null(handle); 953 } 954 } 955 956 957 // Have to have the same name because it's called by a template 958 void nmethod::copy_values(GrowableArray<jobject>* array) { 959 int length = array->length(); 960 assert((address)(oops_begin() + length) <= (address)oops_end(), "oops big enough"); 961 oop* dest = oops_begin(); 962 for (int index = 0 ; index < length; index++) { 963 initialize_immediate_oop(&dest[index], array->at(index)); 964 } 965 966 // Now we can fix up all the oops in the code. We need to do this 967 // in the code because the assembler uses jobjects as placeholders. 968 // The code and relocations have already been initialized by the 969 // CodeBlob constructor, so it is valid even at this early point to 970 // iterate over relocations and patch the code. 971 fix_oop_relocations(NULL, NULL, /*initialize_immediates=*/ true); 972 } 973 974 void nmethod::copy_values(GrowableArray<Metadata*>* array) { 975 int length = array->length(); 976 assert((address)(metadata_begin() + length) <= (address)metadata_end(), "big enough"); 977 Metadata** dest = metadata_begin(); 978 for (int index = 0 ; index < length; index++) { 979 dest[index] = array->at(index); 980 } 981 } 982 983 void nmethod::fix_oop_relocations(address begin, address end, bool initialize_immediates) { 984 // re-patch all oop-bearing instructions, just in case some oops moved 985 RelocIterator iter(this, begin, end); 986 while (iter.next()) { 987 if (iter.type() == relocInfo::oop_type) { 988 oop_Relocation* reloc = iter.oop_reloc(); 989 if (initialize_immediates && reloc->oop_is_immediate()) { 990 oop* dest = reloc->oop_addr(); 991 initialize_immediate_oop(dest, (jobject) *dest); 992 } 993 // Refresh the oop-related bits of this instruction. 994 reloc->fix_oop_relocation(); 995 } else if (iter.type() == relocInfo::metadata_type) { 996 metadata_Relocation* reloc = iter.metadata_reloc(); 997 reloc->fix_metadata_relocation(); 998 } 999 } 1000 } 1001 1002 1003 void nmethod::verify_clean_inline_caches() { 1004 assert(CompiledICLocker::is_safe(this), "mt unsafe call"); 1005 1006 ResourceMark rm; 1007 RelocIterator iter(this, oops_reloc_begin()); 1008 while(iter.next()) { 1009 switch(iter.type()) { 1010 case relocInfo::virtual_call_type: 1011 case relocInfo::opt_virtual_call_type: { 1012 CompiledIC *ic = CompiledIC_at(&iter); 1013 // Ok, to lookup references to zombies here 1014 CodeBlob *cb = CodeCache::find_blob_unsafe(ic->ic_destination()); 1015 assert(cb != NULL, "destination not in CodeBlob?"); 1016 nmethod* nm = cb->as_nmethod_or_null(); 1017 if( nm != NULL ) { 1018 // Verify that inline caches pointing to both zombie and not_entrant methods are clean 1019 if (!nm->is_in_use() || (nm->method()->code() != nm)) { 1020 assert(ic->is_clean(), "IC should be clean"); 1021 } 1022 } 1023 break; 1024 } 1025 case relocInfo::static_call_type: { 1026 CompiledStaticCall *csc = compiledStaticCall_at(iter.reloc()); 1027 CodeBlob *cb = CodeCache::find_blob_unsafe(csc->destination()); 1028 assert(cb != NULL, "destination not in CodeBlob?"); 1029 nmethod* nm = cb->as_nmethod_or_null(); 1030 if( nm != NULL ) { 1031 // Verify that inline caches pointing to both zombie and not_entrant methods are clean 1032 if (!nm->is_in_use() || (nm->method()->code() != nm)) { 1033 assert(csc->is_clean(), "IC should be clean"); 1034 } 1035 } 1036 break; 1037 } 1038 default: 1039 break; 1040 } 1041 } 1042 } 1043 1044 // This is a private interface with the sweeper. 1045 void nmethod::mark_as_seen_on_stack() { 1046 assert(is_alive(), "Must be an alive method"); 1047 // Set the traversal mark to ensure that the sweeper does 2 1048 // cleaning passes before moving to zombie. 1049 set_stack_traversal_mark(NMethodSweeper::traversal_count()); 1050 } 1051 1052 // Tell if a non-entrant method can be converted to a zombie (i.e., 1053 // there are no activations on the stack, not in use by the VM, 1054 // and not in use by the ServiceThread) 1055 bool nmethod::can_convert_to_zombie() { 1056 // Note that this is called when the sweeper has observed the nmethod to be 1057 // not_entrant. However, with concurrent code cache unloading, the state 1058 // might have moved on to unloaded if it is_unloading(), due to racing 1059 // concurrent GC threads. 1060 assert(is_not_entrant() || is_unloading(), "must be a non-entrant method"); 1061 1062 // Since the nmethod sweeper only does partial sweep the sweeper's traversal 1063 // count can be greater than the stack traversal count before it hits the 1064 // nmethod for the second time. 1065 // If an is_unloading() nmethod is still not_entrant, then it is not safe to 1066 // convert it to zombie due to GC unloading interactions. However, if it 1067 // has become unloaded, then it is okay to convert such nmethods to zombie. 1068 return stack_traversal_mark() + 1 < NMethodSweeper::traversal_count() && 1069 !is_locked_by_vm() && (!is_unloading() || is_unloaded()); 1070 } 1071 1072 void nmethod::inc_decompile_count() { 1073 if (!is_compiled_by_c2() && !is_compiled_by_jvmci()) return; 1074 // Could be gated by ProfileTraps, but do not bother... 1075 Method* m = method(); 1076 if (m == NULL) return; 1077 MethodData* mdo = m->method_data(); 1078 if (mdo == NULL) return; 1079 // There is a benign race here. See comments in methodData.hpp. 1080 mdo->inc_decompile_count(); 1081 } 1082 1083 void nmethod::make_unloaded() { 1084 post_compiled_method_unload(); 1085 1086 // This nmethod is being unloaded, make sure that dependencies 1087 // recorded in instanceKlasses get flushed. 1088 // Since this work is being done during a GC, defer deleting dependencies from the 1089 // InstanceKlass. 1090 assert(Universe::heap()->is_gc_active() || Thread::current()->is_ConcurrentGC_thread(), 1091 "should only be called during gc"); 1092 flush_dependencies(/*delete_immediately*/false); 1093 1094 // Break cycle between nmethod & method 1095 LogTarget(Trace, class, unload, nmethod) lt; 1096 if (lt.is_enabled()) { 1097 LogStream ls(lt); 1098 ls.print("making nmethod " INTPTR_FORMAT 1099 " unloadable, Method*(" INTPTR_FORMAT 1100 ") ", 1101 p2i(this), p2i(_method)); 1102 ls.cr(); 1103 } 1104 // Unlink the osr method, so we do not look this up again 1105 if (is_osr_method()) { 1106 // Invalidate the osr nmethod only once 1107 if (is_in_use()) { 1108 invalidate_osr_method(); 1109 } 1110 #ifdef ASSERT 1111 if (method() != NULL) { 1112 // Make sure osr nmethod is invalidated, i.e. not on the list 1113 bool found = method()->method_holder()->remove_osr_nmethod(this); 1114 assert(!found, "osr nmethod should have been invalidated"); 1115 } 1116 #endif 1117 } 1118 1119 // If _method is already NULL the Method* is about to be unloaded, 1120 // so we don't have to break the cycle. Note that it is possible to 1121 // have the Method* live here, in case we unload the nmethod because 1122 // it is pointing to some oop (other than the Method*) being unloaded. 1123 Method::unlink_code(_method, this); // Break a cycle 1124 1125 // Make the class unloaded - i.e., change state and notify sweeper 1126 assert(SafepointSynchronize::is_at_safepoint() || Thread::current()->is_ConcurrentGC_thread(), 1127 "must be at safepoint"); 1128 1129 { 1130 // Clear ICStubs and release any CompiledICHolders. 1131 CompiledICLocker ml(this); 1132 clear_ic_callsites(); 1133 } 1134 1135 // Unregister must be done before the state change 1136 { 1137 MutexLocker ml(SafepointSynchronize::is_at_safepoint() ? NULL : CodeCache_lock, 1138 Mutex::_no_safepoint_check_flag); 1139 Universe::heap()->unregister_nmethod(this); 1140 CodeCache::unregister_old_nmethod(this); 1141 } 1142 1143 // Clear the method of this dead nmethod 1144 set_method(NULL); 1145 1146 // Log the unloading. 1147 log_state_change(); 1148 1149 // The Method* is gone at this point 1150 assert(_method == NULL, "Tautology"); 1151 1152 set_osr_link(NULL); 1153 NMethodSweeper::report_state_change(this); 1154 1155 // The release is only needed for compile-time ordering, as accesses 1156 // into the nmethod after the store are not safe due to the sweeper 1157 // being allowed to free it when the store is observed, during 1158 // concurrent nmethod unloading. Therefore, there is no need for 1159 // acquire on the loader side. 1160 OrderAccess::release_store(&_state, (signed char)unloaded); 1161 1162 #if INCLUDE_JVMCI 1163 // Clear the link between this nmethod and a HotSpotNmethod mirror 1164 JVMCINMethodData* nmethod_data = jvmci_nmethod_data(); 1165 if (nmethod_data != NULL) { 1166 nmethod_data->invalidate_nmethod_mirror(this); 1167 nmethod_data->clear_nmethod_mirror(this); 1168 } 1169 #endif 1170 } 1171 1172 void nmethod::invalidate_osr_method() { 1173 assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod"); 1174 // Remove from list of active nmethods 1175 if (method() != NULL) { 1176 method()->method_holder()->remove_osr_nmethod(this); 1177 } 1178 } 1179 1180 void nmethod::log_state_change() const { 1181 if (LogCompilation) { 1182 if (xtty != NULL) { 1183 ttyLocker ttyl; // keep the following output all in one block 1184 if (_state == unloaded) { 1185 xtty->begin_elem("make_unloaded thread='" UINTX_FORMAT "'", 1186 os::current_thread_id()); 1187 } else { 1188 xtty->begin_elem("make_not_entrant thread='" UINTX_FORMAT "'%s", 1189 os::current_thread_id(), 1190 (_state == zombie ? " zombie='1'" : "")); 1191 } 1192 log_identity(xtty); 1193 xtty->stamp(); 1194 xtty->end_elem(); 1195 } 1196 } 1197 1198 const char *state_msg = _state == zombie ? "made zombie" : "made not entrant"; 1199 CompileTask::print_ul(this, state_msg); 1200 if (PrintCompilation && _state != unloaded) { 1201 print_on(tty, state_msg); 1202 } 1203 } 1204 1205 void nmethod::unlink_from_method() { 1206 // We need to check if both the _code and _from_compiled_code_entry_point 1207 // refer to this nmethod because there is a race in setting these two fields 1208 // in Method* as seen in bugid 4947125. 1209 // If the vep() points to the zombie nmethod, the memory for the nmethod 1210 // could be flushed and the compiler and vtable stubs could still call 1211 // through it. 1212 Method::unlink_code(method(), this); 1213 } 1214 1215 /** 1216 * Common functionality for both make_not_entrant and make_zombie 1217 */ 1218 bool nmethod::make_not_entrant_or_zombie(int state) { 1219 assert(state == zombie || state == not_entrant, "must be zombie or not_entrant"); 1220 assert(!is_zombie(), "should not already be a zombie"); 1221 1222 if (_state == state) { 1223 // Avoid taking the lock if already in required state. 1224 // This is safe from races because the state is an end-state, 1225 // which the nmethod cannot back out of once entered. 1226 // No need for fencing either. 1227 return false; 1228 } 1229 1230 // Make sure neither the nmethod nor the method is flushed in case of a safepoint in code below. 1231 nmethodLocker nml(this); 1232 methodHandle the_method(method()); 1233 // This can be called while the system is already at a safepoint which is ok 1234 NoSafepointVerifier nsv(true, !SafepointSynchronize::is_at_safepoint()); 1235 1236 // during patching, depending on the nmethod state we must notify the GC that 1237 // code has been unloaded, unregistering it. We cannot do this right while 1238 // holding the CompiledMethod_lock because we need to use the CodeCache_lock. This 1239 // would be prone to deadlocks. 1240 // This flag is used to remember whether we need to later lock and unregister. 1241 bool nmethod_needs_unregister = false; 1242 1243 // invalidate osr nmethod before acquiring the patching lock since 1244 // they both acquire leaf locks and we don't want a deadlock. 1245 // This logic is equivalent to the logic below for patching the 1246 // verified entry point of regular methods. We check that the 1247 // nmethod is in use to ensure that it is invalidated only once. 1248 if (is_osr_method() && is_in_use()) { 1249 // this effectively makes the osr nmethod not entrant 1250 invalidate_osr_method(); 1251 } 1252 1253 { 1254 // Enter critical section. Does not block for safepoint. 1255 MutexLocker pl(CompiledMethod_lock, Mutex::_no_safepoint_check_flag); 1256 1257 if (_state == state) { 1258 // another thread already performed this transition so nothing 1259 // to do, but return false to indicate this. 1260 return false; 1261 } 1262 1263 // The caller can be calling the method statically or through an inline 1264 // cache call. 1265 if (!is_osr_method() && !is_not_entrant()) { 1266 NativeJump::patch_verified_entry(entry_point(), verified_entry_point(), 1267 SharedRuntime::get_handle_wrong_method_stub()); 1268 } 1269 1270 if (is_in_use() && update_recompile_counts()) { 1271 // It's a true state change, so mark the method as decompiled. 1272 // Do it only for transition from alive. 1273 inc_decompile_count(); 1274 } 1275 1276 // If the state is becoming a zombie, signal to unregister the nmethod with 1277 // the heap. 1278 // This nmethod may have already been unloaded during a full GC. 1279 if ((state == zombie) && !is_unloaded()) { 1280 nmethod_needs_unregister = true; 1281 } 1282 1283 // Must happen before state change. Otherwise we have a race condition in 1284 // nmethod::can_not_entrant_be_converted(). I.e., a method can immediately 1285 // transition its state from 'not_entrant' to 'zombie' without having to wait 1286 // for stack scanning. 1287 if (state == not_entrant) { 1288 mark_as_seen_on_stack(); 1289 OrderAccess::storestore(); // _stack_traversal_mark and _state 1290 } 1291 1292 // Change state 1293 _state = state; 1294 1295 // Log the transition once 1296 log_state_change(); 1297 1298 // Remove nmethod from method. 1299 unlink_from_method(); 1300 1301 } // leave critical region under CompiledMethod_lock 1302 1303 #if INCLUDE_JVMCI 1304 // Invalidate can't occur while holding the Patching lock 1305 JVMCINMethodData* nmethod_data = jvmci_nmethod_data(); 1306 if (nmethod_data != NULL) { 1307 nmethod_data->invalidate_nmethod_mirror(this); 1308 } 1309 #endif 1310 1311 #ifdef ASSERT 1312 if (is_osr_method() && method() != NULL) { 1313 // Make sure osr nmethod is invalidated, i.e. not on the list 1314 bool found = method()->method_holder()->remove_osr_nmethod(this); 1315 assert(!found, "osr nmethod should have been invalidated"); 1316 } 1317 #endif 1318 1319 // When the nmethod becomes zombie it is no longer alive so the 1320 // dependencies must be flushed. nmethods in the not_entrant 1321 // state will be flushed later when the transition to zombie 1322 // happens or they get unloaded. 1323 if (state == zombie) { 1324 { 1325 // Flushing dependencies must be done before any possible 1326 // safepoint can sneak in, otherwise the oops used by the 1327 // dependency logic could have become stale. 1328 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1329 if (nmethod_needs_unregister) { 1330 Universe::heap()->unregister_nmethod(this); 1331 CodeCache::unregister_old_nmethod(this); 1332 } 1333 flush_dependencies(/*delete_immediately*/true); 1334 } 1335 1336 #if INCLUDE_JVMCI 1337 // Now that the nmethod has been unregistered, it's 1338 // safe to clear the HotSpotNmethod mirror oop. 1339 if (nmethod_data != NULL) { 1340 nmethod_data->clear_nmethod_mirror(this); 1341 } 1342 #endif 1343 1344 // Clear ICStubs to prevent back patching stubs of zombie or flushed 1345 // nmethods during the next safepoint (see ICStub::finalize), as well 1346 // as to free up CompiledICHolder resources. 1347 { 1348 CompiledICLocker ml(this); 1349 clear_ic_callsites(); 1350 } 1351 1352 // zombie only - if a JVMTI agent has enabled the CompiledMethodUnload 1353 // event and it hasn't already been reported for this nmethod then 1354 // report it now. The event may have been reported earlier if the GC 1355 // marked it for unloading). JvmtiDeferredEventQueue support means 1356 // we no longer go to a safepoint here. 1357 post_compiled_method_unload(); 1358 1359 #ifdef ASSERT 1360 // It's no longer safe to access the oops section since zombie 1361 // nmethods aren't scanned for GC. 1362 _oops_are_stale = true; 1363 #endif 1364 // the Method may be reclaimed by class unloading now that the 1365 // nmethod is in zombie state 1366 set_method(NULL); 1367 } else { 1368 assert(state == not_entrant, "other cases may need to be handled differently"); 1369 } 1370 1371 if (TraceCreateZombies && state == zombie) { 1372 ResourceMark m; 1373 tty->print_cr("nmethod <" INTPTR_FORMAT "> %s code made %s", p2i(this), this->method() ? this->method()->name_and_sig_as_C_string() : "null", (state == not_entrant) ? "not entrant" : "zombie"); 1374 } 1375 1376 NMethodSweeper::report_state_change(this); 1377 return true; 1378 } 1379 1380 void nmethod::flush() { 1381 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1382 // Note that there are no valid oops in the nmethod anymore. 1383 assert(!is_osr_method() || is_unloaded() || is_zombie(), 1384 "osr nmethod must be unloaded or zombie before flushing"); 1385 assert(is_zombie() || is_osr_method(), "must be a zombie method"); 1386 assert (!is_locked_by_vm(), "locked methods shouldn't be flushed"); 1387 assert_locked_or_safepoint(CodeCache_lock); 1388 1389 // completely deallocate this method 1390 Events::log(JavaThread::current(), "flushing nmethod " INTPTR_FORMAT, p2i(this)); 1391 if (PrintMethodFlushing) { 1392 tty->print_cr("*flushing %s nmethod %3d/" INTPTR_FORMAT ". Live blobs:" UINT32_FORMAT 1393 "/Free CodeCache:" SIZE_FORMAT "Kb", 1394 is_osr_method() ? "osr" : "",_compile_id, p2i(this), CodeCache::blob_count(), 1395 CodeCache::unallocated_capacity(CodeCache::get_code_blob_type(this))/1024); 1396 } 1397 1398 // We need to deallocate any ExceptionCache data. 1399 // Note that we do not need to grab the nmethod lock for this, it 1400 // better be thread safe if we're disposing of it! 1401 ExceptionCache* ec = exception_cache(); 1402 set_exception_cache(NULL); 1403 while(ec != NULL) { 1404 ExceptionCache* next = ec->next(); 1405 delete ec; 1406 ec = next; 1407 } 1408 1409 Universe::heap()->flush_nmethod(this); 1410 1411 CodeBlob::flush(); 1412 CodeCache::free(this); 1413 } 1414 1415 oop nmethod::oop_at(int index) const { 1416 if (index == 0) { 1417 return NULL; 1418 } 1419 return NativeAccess<AS_NO_KEEPALIVE>::oop_load(oop_addr_at(index)); 1420 } 1421 1422 // 1423 // Notify all classes this nmethod is dependent on that it is no 1424 // longer dependent. This should only be called in two situations. 1425 // First, when a nmethod transitions to a zombie all dependents need 1426 // to be clear. Since zombification happens at a safepoint there's no 1427 // synchronization issues. The second place is a little more tricky. 1428 // During phase 1 of mark sweep class unloading may happen and as a 1429 // result some nmethods may get unloaded. In this case the flushing 1430 // of dependencies must happen during phase 1 since after GC any 1431 // dependencies in the unloaded nmethod won't be updated, so 1432 // traversing the dependency information in unsafe. In that case this 1433 // function is called with a boolean argument and this function only 1434 // notifies instanceKlasses that are reachable 1435 1436 void nmethod::flush_dependencies(bool delete_immediately) { 1437 DEBUG_ONLY(bool called_by_gc = Universe::heap()->is_gc_active() || Thread::current()->is_ConcurrentGC_thread();) 1438 assert(called_by_gc != delete_immediately, 1439 "delete_immediately is false if and only if we are called during GC"); 1440 if (!has_flushed_dependencies()) { 1441 set_has_flushed_dependencies(); 1442 for (Dependencies::DepStream deps(this); deps.next(); ) { 1443 if (deps.type() == Dependencies::call_site_target_value) { 1444 // CallSite dependencies are managed on per-CallSite instance basis. 1445 oop call_site = deps.argument_oop(0); 1446 if (delete_immediately) { 1447 assert_locked_or_safepoint(CodeCache_lock); 1448 MethodHandles::remove_dependent_nmethod(call_site, this); 1449 } else { 1450 MethodHandles::clean_dependency_context(call_site); 1451 } 1452 } else { 1453 Klass* klass = deps.context_type(); 1454 if (klass == NULL) { 1455 continue; // ignore things like evol_method 1456 } 1457 // During GC delete_immediately is false, and liveness 1458 // of dependee determines class that needs to be updated. 1459 if (delete_immediately) { 1460 assert_locked_or_safepoint(CodeCache_lock); 1461 InstanceKlass::cast(klass)->remove_dependent_nmethod(this); 1462 } else if (klass->is_loader_alive()) { 1463 // The GC may clean dependency contexts concurrently and in parallel. 1464 InstanceKlass::cast(klass)->clean_dependency_context(); 1465 } 1466 } 1467 } 1468 } 1469 } 1470 1471 // ------------------------------------------------------------------ 1472 // post_compiled_method_load_event 1473 // new method for install_code() path 1474 // Transfer information from compilation to jvmti 1475 void nmethod::post_compiled_method_load_event() { 1476 1477 Method* moop = method(); 1478 HOTSPOT_COMPILED_METHOD_LOAD( 1479 (char *) moop->klass_name()->bytes(), 1480 moop->klass_name()->utf8_length(), 1481 (char *) moop->name()->bytes(), 1482 moop->name()->utf8_length(), 1483 (char *) moop->signature()->bytes(), 1484 moop->signature()->utf8_length(), 1485 insts_begin(), insts_size()); 1486 1487 if (JvmtiExport::should_post_compiled_method_load() || 1488 JvmtiExport::should_post_compiled_method_unload()) { 1489 get_and_cache_jmethod_id(); 1490 } 1491 1492 if (JvmtiExport::should_post_compiled_method_load()) { 1493 // Let the Service thread (which is a real Java thread) post the event 1494 MutexLocker ml(Service_lock, Mutex::_no_safepoint_check_flag); 1495 JvmtiDeferredEventQueue::enqueue( 1496 JvmtiDeferredEvent::compiled_method_load_event(this)); 1497 } 1498 } 1499 1500 jmethodID nmethod::get_and_cache_jmethod_id() { 1501 if (_jmethod_id == NULL) { 1502 // Cache the jmethod_id since it can no longer be looked up once the 1503 // method itself has been marked for unloading. 1504 _jmethod_id = method()->jmethod_id(); 1505 } 1506 return _jmethod_id; 1507 } 1508 1509 void nmethod::post_compiled_method_unload() { 1510 if (unload_reported()) { 1511 // During unloading we transition to unloaded and then to zombie 1512 // and the unloading is reported during the first transition. 1513 return; 1514 } 1515 1516 assert(_method != NULL && !is_unloaded(), "just checking"); 1517 DTRACE_METHOD_UNLOAD_PROBE(method()); 1518 1519 // If a JVMTI agent has enabled the CompiledMethodUnload event then 1520 // post the event. Sometime later this nmethod will be made a zombie 1521 // by the sweeper but the Method* will not be valid at that point. 1522 // If the _jmethod_id is null then no load event was ever requested 1523 // so don't bother posting the unload. The main reason for this is 1524 // that the jmethodID is a weak reference to the Method* so if 1525 // it's being unloaded there's no way to look it up since the weak 1526 // ref will have been cleared. 1527 if (_jmethod_id != NULL && JvmtiExport::should_post_compiled_method_unload()) { 1528 assert(!unload_reported(), "already unloaded"); 1529 JvmtiDeferredEvent event = 1530 JvmtiDeferredEvent::compiled_method_unload_event(this, 1531 _jmethod_id, insts_begin()); 1532 MutexLocker ml(Service_lock, Mutex::_no_safepoint_check_flag); 1533 JvmtiDeferredEventQueue::enqueue(event); 1534 } 1535 1536 // The JVMTI CompiledMethodUnload event can be enabled or disabled at 1537 // any time. As the nmethod is being unloaded now we mark it has 1538 // having the unload event reported - this will ensure that we don't 1539 // attempt to report the event in the unlikely scenario where the 1540 // event is enabled at the time the nmethod is made a zombie. 1541 set_unload_reported(); 1542 } 1543 1544 // Iterate over metadata calling this function. Used by RedefineClasses 1545 void nmethod::metadata_do(MetadataClosure* f) { 1546 { 1547 // Visit all immediate references that are embedded in the instruction stream. 1548 RelocIterator iter(this, oops_reloc_begin()); 1549 while (iter.next()) { 1550 if (iter.type() == relocInfo::metadata_type ) { 1551 metadata_Relocation* r = iter.metadata_reloc(); 1552 // In this metadata, we must only follow those metadatas directly embedded in 1553 // the code. Other metadatas (oop_index>0) are seen as part of 1554 // the metadata section below. 1555 assert(1 == (r->metadata_is_immediate()) + 1556 (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()), 1557 "metadata must be found in exactly one place"); 1558 if (r->metadata_is_immediate() && r->metadata_value() != NULL) { 1559 Metadata* md = r->metadata_value(); 1560 if (md != _method) f->do_metadata(md); 1561 } 1562 } else if (iter.type() == relocInfo::virtual_call_type) { 1563 // Check compiledIC holders associated with this nmethod 1564 ResourceMark rm; 1565 CompiledIC *ic = CompiledIC_at(&iter); 1566 if (ic->is_icholder_call()) { 1567 CompiledICHolder* cichk = ic->cached_icholder(); 1568 f->do_metadata(cichk->holder_metadata()); 1569 f->do_metadata(cichk->holder_klass()); 1570 } else { 1571 Metadata* ic_oop = ic->cached_metadata(); 1572 if (ic_oop != NULL) { 1573 f->do_metadata(ic_oop); 1574 } 1575 } 1576 } 1577 } 1578 } 1579 1580 // Visit the metadata section 1581 for (Metadata** p = metadata_begin(); p < metadata_end(); p++) { 1582 if (*p == Universe::non_oop_word() || *p == NULL) continue; // skip non-oops 1583 Metadata* md = *p; 1584 f->do_metadata(md); 1585 } 1586 1587 // Visit metadata not embedded in the other places. 1588 if (_method != NULL) f->do_metadata(_method); 1589 } 1590 1591 // The _is_unloading_state encodes a tuple comprising the unloading cycle 1592 // and the result of IsUnloadingBehaviour::is_unloading() fpr that cycle. 1593 // This is the bit layout of the _is_unloading_state byte: 00000CCU 1594 // CC refers to the cycle, which has 2 bits, and U refers to the result of 1595 // IsUnloadingBehaviour::is_unloading() for that unloading cycle. 1596 1597 class IsUnloadingState: public AllStatic { 1598 static const uint8_t _is_unloading_mask = 1; 1599 static const uint8_t _is_unloading_shift = 0; 1600 static const uint8_t _unloading_cycle_mask = 6; 1601 static const uint8_t _unloading_cycle_shift = 1; 1602 1603 static uint8_t set_is_unloading(uint8_t state, bool value) { 1604 state &= ~_is_unloading_mask; 1605 if (value) { 1606 state |= 1 << _is_unloading_shift; 1607 } 1608 assert(is_unloading(state) == value, "unexpected unloading cycle overflow"); 1609 return state; 1610 } 1611 1612 static uint8_t set_unloading_cycle(uint8_t state, uint8_t value) { 1613 state &= ~_unloading_cycle_mask; 1614 state |= value << _unloading_cycle_shift; 1615 assert(unloading_cycle(state) == value, "unexpected unloading cycle overflow"); 1616 return state; 1617 } 1618 1619 public: 1620 static bool is_unloading(uint8_t state) { return (state & _is_unloading_mask) >> _is_unloading_shift == 1; } 1621 static uint8_t unloading_cycle(uint8_t state) { return (state & _unloading_cycle_mask) >> _unloading_cycle_shift; } 1622 1623 static uint8_t create(bool is_unloading, uint8_t unloading_cycle) { 1624 uint8_t state = 0; 1625 state = set_is_unloading(state, is_unloading); 1626 state = set_unloading_cycle(state, unloading_cycle); 1627 return state; 1628 } 1629 }; 1630 1631 bool nmethod::is_unloading() { 1632 uint8_t state = RawAccess<MO_RELAXED>::load(&_is_unloading_state); 1633 bool state_is_unloading = IsUnloadingState::is_unloading(state); 1634 uint8_t state_unloading_cycle = IsUnloadingState::unloading_cycle(state); 1635 if (state_is_unloading) { 1636 return true; 1637 } 1638 uint8_t current_cycle = CodeCache::unloading_cycle(); 1639 if (state_unloading_cycle == current_cycle) { 1640 return false; 1641 } 1642 1643 // The IsUnloadingBehaviour is responsible for checking if there are any dead 1644 // oops in the CompiledMethod, by calling oops_do on it. 1645 state_unloading_cycle = current_cycle; 1646 1647 if (is_zombie()) { 1648 // Zombies without calculated unloading epoch are never unloading due to GC. 1649 1650 // There are no races where a previously observed is_unloading() nmethod 1651 // suddenly becomes not is_unloading() due to here being observed as zombie. 1652 1653 // With STW unloading, all is_alive() && is_unloading() nmethods are unlinked 1654 // and unloaded in the safepoint. That makes races where an nmethod is first 1655 // observed as is_alive() && is_unloading() and subsequently observed as 1656 // is_zombie() impossible. 1657 1658 // With concurrent unloading, all references to is_unloading() nmethods are 1659 // first unlinked (e.g. IC caches and dependency contexts). Then a global 1660 // handshake operation is performed with all JavaThreads before finally 1661 // unloading the nmethods. The sweeper never converts is_alive() && is_unloading() 1662 // nmethods to zombies; it waits for them to become is_unloaded(). So before 1663 // the global handshake, it is impossible for is_unloading() nmethods to 1664 // racingly become is_zombie(). And is_unloading() is calculated for all is_alive() 1665 // nmethods before taking that global handshake, meaning that it will never 1666 // be recalculated after the handshake. 1667 1668 // After that global handshake, is_unloading() nmethods are only observable 1669 // to the iterators, and they will never trigger recomputation of the cached 1670 // is_unloading_state, and hence may not suffer from such races. 1671 1672 state_is_unloading = false; 1673 } else { 1674 state_is_unloading = IsUnloadingBehaviour::current()->is_unloading(this); 1675 } 1676 1677 state = IsUnloadingState::create(state_is_unloading, state_unloading_cycle); 1678 1679 RawAccess<MO_RELAXED>::store(&_is_unloading_state, state); 1680 1681 return state_is_unloading; 1682 } 1683 1684 void nmethod::clear_unloading_state() { 1685 uint8_t state = IsUnloadingState::create(false, CodeCache::unloading_cycle()); 1686 RawAccess<MO_RELAXED>::store(&_is_unloading_state, state); 1687 } 1688 1689 1690 // This is called at the end of the strong tracing/marking phase of a 1691 // GC to unload an nmethod if it contains otherwise unreachable 1692 // oops. 1693 1694 void nmethod::do_unloading(bool unloading_occurred) { 1695 // Make sure the oop's ready to receive visitors 1696 assert(!is_zombie() && !is_unloaded(), 1697 "should not call follow on zombie or unloaded nmethod"); 1698 1699 if (is_unloading()) { 1700 make_unloaded(); 1701 } else { 1702 guarantee(unload_nmethod_caches(unloading_occurred), 1703 "Should not need transition stubs"); 1704 } 1705 } 1706 1707 void nmethod::oops_do(OopClosure* f, bool allow_zombie) { 1708 // make sure the oops ready to receive visitors 1709 assert(allow_zombie || !is_zombie(), "should not call follow on zombie nmethod"); 1710 assert(!is_unloaded(), "should not call follow on unloaded nmethod"); 1711 1712 // Prevent extra code cache walk for platforms that don't have immediate oops. 1713 if (relocInfo::mustIterateImmediateOopsInCode()) { 1714 RelocIterator iter(this, oops_reloc_begin()); 1715 1716 while (iter.next()) { 1717 if (iter.type() == relocInfo::oop_type ) { 1718 oop_Relocation* r = iter.oop_reloc(); 1719 // In this loop, we must only follow those oops directly embedded in 1720 // the code. Other oops (oop_index>0) are seen as part of scopes_oops. 1721 assert(1 == (r->oop_is_immediate()) + 1722 (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()), 1723 "oop must be found in exactly one place"); 1724 if (r->oop_is_immediate() && r->oop_value() != NULL) { 1725 f->do_oop(r->oop_addr()); 1726 } 1727 } 1728 } 1729 } 1730 1731 // Scopes 1732 // This includes oop constants not inlined in the code stream. 1733 for (oop* p = oops_begin(); p < oops_end(); p++) { 1734 if (*p == Universe::non_oop_word()) continue; // skip non-oops 1735 f->do_oop(p); 1736 } 1737 } 1738 1739 #define NMETHOD_SENTINEL ((nmethod*)badAddress) 1740 1741 nmethod* volatile nmethod::_oops_do_mark_nmethods; 1742 1743 // An nmethod is "marked" if its _mark_link is set non-null. 1744 // Even if it is the end of the linked list, it will have a non-null link value, 1745 // as long as it is on the list. 1746 // This code must be MP safe, because it is used from parallel GC passes. 1747 bool nmethod::test_set_oops_do_mark() { 1748 assert(nmethod::oops_do_marking_is_active(), "oops_do_marking_prologue must be called"); 1749 if (_oops_do_mark_link == NULL) { 1750 // Claim this nmethod for this thread to mark. 1751 if (Atomic::replace_if_null(NMETHOD_SENTINEL, &_oops_do_mark_link)) { 1752 // Atomically append this nmethod (now claimed) to the head of the list: 1753 nmethod* observed_mark_nmethods = _oops_do_mark_nmethods; 1754 for (;;) { 1755 nmethod* required_mark_nmethods = observed_mark_nmethods; 1756 _oops_do_mark_link = required_mark_nmethods; 1757 observed_mark_nmethods = 1758 Atomic::cmpxchg(this, &_oops_do_mark_nmethods, required_mark_nmethods); 1759 if (observed_mark_nmethods == required_mark_nmethods) 1760 break; 1761 } 1762 // Mark was clear when we first saw this guy. 1763 LogTarget(Trace, gc, nmethod) lt; 1764 if (lt.is_enabled()) { 1765 LogStream ls(lt); 1766 CompileTask::print(&ls, this, "oops_do, mark", /*short_form:*/ true); 1767 } 1768 return false; 1769 } 1770 } 1771 // On fall through, another racing thread marked this nmethod before we did. 1772 return true; 1773 } 1774 1775 void nmethod::oops_do_marking_prologue() { 1776 log_trace(gc, nmethod)("oops_do_marking_prologue"); 1777 assert(_oops_do_mark_nmethods == NULL, "must not call oops_do_marking_prologue twice in a row"); 1778 // We use cmpxchg instead of regular assignment here because the user 1779 // may fork a bunch of threads, and we need them all to see the same state. 1780 nmethod* observed = Atomic::cmpxchg(NMETHOD_SENTINEL, &_oops_do_mark_nmethods, (nmethod*)NULL); 1781 guarantee(observed == NULL, "no races in this sequential code"); 1782 } 1783 1784 void nmethod::oops_do_marking_epilogue() { 1785 assert(_oops_do_mark_nmethods != NULL, "must not call oops_do_marking_epilogue twice in a row"); 1786 nmethod* cur = _oops_do_mark_nmethods; 1787 while (cur != NMETHOD_SENTINEL) { 1788 assert(cur != NULL, "not NULL-terminated"); 1789 nmethod* next = cur->_oops_do_mark_link; 1790 cur->_oops_do_mark_link = NULL; 1791 DEBUG_ONLY(cur->verify_oop_relocations()); 1792 1793 LogTarget(Trace, gc, nmethod) lt; 1794 if (lt.is_enabled()) { 1795 LogStream ls(lt); 1796 CompileTask::print(&ls, cur, "oops_do, unmark", /*short_form:*/ true); 1797 } 1798 cur = next; 1799 } 1800 nmethod* required = _oops_do_mark_nmethods; 1801 nmethod* observed = Atomic::cmpxchg((nmethod*)NULL, &_oops_do_mark_nmethods, required); 1802 guarantee(observed == required, "no races in this sequential code"); 1803 log_trace(gc, nmethod)("oops_do_marking_epilogue"); 1804 } 1805 1806 inline bool includes(void* p, void* from, void* to) { 1807 return from <= p && p < to; 1808 } 1809 1810 1811 void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) { 1812 assert(count >= 2, "must be sentinel values, at least"); 1813 1814 #ifdef ASSERT 1815 // must be sorted and unique; we do a binary search in find_pc_desc() 1816 int prev_offset = pcs[0].pc_offset(); 1817 assert(prev_offset == PcDesc::lower_offset_limit, 1818 "must start with a sentinel"); 1819 for (int i = 1; i < count; i++) { 1820 int this_offset = pcs[i].pc_offset(); 1821 assert(this_offset > prev_offset, "offsets must be sorted"); 1822 prev_offset = this_offset; 1823 } 1824 assert(prev_offset == PcDesc::upper_offset_limit, 1825 "must end with a sentinel"); 1826 #endif //ASSERT 1827 1828 // Search for MethodHandle invokes and tag the nmethod. 1829 for (int i = 0; i < count; i++) { 1830 if (pcs[i].is_method_handle_invoke()) { 1831 set_has_method_handle_invokes(true); 1832 break; 1833 } 1834 } 1835 assert(has_method_handle_invokes() == (_deopt_mh_handler_begin != NULL), "must have deopt mh handler"); 1836 1837 int size = count * sizeof(PcDesc); 1838 assert(scopes_pcs_size() >= size, "oob"); 1839 memcpy(scopes_pcs_begin(), pcs, size); 1840 1841 // Adjust the final sentinel downward. 1842 PcDesc* last_pc = &scopes_pcs_begin()[count-1]; 1843 assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity"); 1844 last_pc->set_pc_offset(content_size() + 1); 1845 for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) { 1846 // Fill any rounding gaps with copies of the last record. 1847 last_pc[1] = last_pc[0]; 1848 } 1849 // The following assert could fail if sizeof(PcDesc) is not 1850 // an integral multiple of oopSize (the rounding term). 1851 // If it fails, change the logic to always allocate a multiple 1852 // of sizeof(PcDesc), and fill unused words with copies of *last_pc. 1853 assert(last_pc + 1 == scopes_pcs_end(), "must match exactly"); 1854 } 1855 1856 void nmethod::copy_scopes_data(u_char* buffer, int size) { 1857 assert(scopes_data_size() >= size, "oob"); 1858 memcpy(scopes_data_begin(), buffer, size); 1859 } 1860 1861 #ifdef ASSERT 1862 static PcDesc* linear_search(const PcDescSearch& search, int pc_offset, bool approximate) { 1863 PcDesc* lower = search.scopes_pcs_begin(); 1864 PcDesc* upper = search.scopes_pcs_end(); 1865 lower += 1; // exclude initial sentinel 1866 PcDesc* res = NULL; 1867 for (PcDesc* p = lower; p < upper; p++) { 1868 NOT_PRODUCT(--pc_nmethod_stats.pc_desc_tests); // don't count this call to match_desc 1869 if (match_desc(p, pc_offset, approximate)) { 1870 if (res == NULL) 1871 res = p; 1872 else 1873 res = (PcDesc*) badAddress; 1874 } 1875 } 1876 return res; 1877 } 1878 #endif 1879 1880 1881 // Finds a PcDesc with real-pc equal to "pc" 1882 PcDesc* PcDescContainer::find_pc_desc_internal(address pc, bool approximate, const PcDescSearch& search) { 1883 address base_address = search.code_begin(); 1884 if ((pc < base_address) || 1885 (pc - base_address) >= (ptrdiff_t) PcDesc::upper_offset_limit) { 1886 return NULL; // PC is wildly out of range 1887 } 1888 int pc_offset = (int) (pc - base_address); 1889 1890 // Check the PcDesc cache if it contains the desired PcDesc 1891 // (This as an almost 100% hit rate.) 1892 PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate); 1893 if (res != NULL) { 1894 assert(res == linear_search(search, pc_offset, approximate), "cache ok"); 1895 return res; 1896 } 1897 1898 // Fallback algorithm: quasi-linear search for the PcDesc 1899 // Find the last pc_offset less than the given offset. 1900 // The successor must be the required match, if there is a match at all. 1901 // (Use a fixed radix to avoid expensive affine pointer arithmetic.) 1902 PcDesc* lower = search.scopes_pcs_begin(); 1903 PcDesc* upper = search.scopes_pcs_end(); 1904 upper -= 1; // exclude final sentinel 1905 if (lower >= upper) return NULL; // native method; no PcDescs at all 1906 1907 #define assert_LU_OK \ 1908 /* invariant on lower..upper during the following search: */ \ 1909 assert(lower->pc_offset() < pc_offset, "sanity"); \ 1910 assert(upper->pc_offset() >= pc_offset, "sanity") 1911 assert_LU_OK; 1912 1913 // Use the last successful return as a split point. 1914 PcDesc* mid = _pc_desc_cache.last_pc_desc(); 1915 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches); 1916 if (mid->pc_offset() < pc_offset) { 1917 lower = mid; 1918 } else { 1919 upper = mid; 1920 } 1921 1922 // Take giant steps at first (4096, then 256, then 16, then 1) 1923 const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ debug_only(-1); 1924 const int RADIX = (1 << LOG2_RADIX); 1925 for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) { 1926 while ((mid = lower + step) < upper) { 1927 assert_LU_OK; 1928 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches); 1929 if (mid->pc_offset() < pc_offset) { 1930 lower = mid; 1931 } else { 1932 upper = mid; 1933 break; 1934 } 1935 } 1936 assert_LU_OK; 1937 } 1938 1939 // Sneak up on the value with a linear search of length ~16. 1940 while (true) { 1941 assert_LU_OK; 1942 mid = lower + 1; 1943 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches); 1944 if (mid->pc_offset() < pc_offset) { 1945 lower = mid; 1946 } else { 1947 upper = mid; 1948 break; 1949 } 1950 } 1951 #undef assert_LU_OK 1952 1953 if (match_desc(upper, pc_offset, approximate)) { 1954 assert(upper == linear_search(search, pc_offset, approximate), "search ok"); 1955 _pc_desc_cache.add_pc_desc(upper); 1956 return upper; 1957 } else { 1958 assert(NULL == linear_search(search, pc_offset, approximate), "search ok"); 1959 return NULL; 1960 } 1961 } 1962 1963 1964 void nmethod::check_all_dependencies(DepChange& changes) { 1965 // Checked dependencies are allocated into this ResourceMark 1966 ResourceMark rm; 1967 1968 // Turn off dependency tracing while actually testing dependencies. 1969 NOT_PRODUCT( FlagSetting fs(TraceDependencies, false) ); 1970 1971 typedef ResourceHashtable<DependencySignature, int, &DependencySignature::hash, 1972 &DependencySignature::equals, 11027> DepTable; 1973 1974 DepTable* table = new DepTable(); 1975 1976 // Iterate over live nmethods and check dependencies of all nmethods that are not 1977 // marked for deoptimization. A particular dependency is only checked once. 1978 NMethodIterator iter(NMethodIterator::only_alive_and_not_unloading); 1979 while(iter.next()) { 1980 nmethod* nm = iter.method(); 1981 // Only notify for live nmethods 1982 if (!nm->is_marked_for_deoptimization()) { 1983 for (Dependencies::DepStream deps(nm); deps.next(); ) { 1984 // Construct abstraction of a dependency. 1985 DependencySignature* current_sig = new DependencySignature(deps); 1986 1987 // Determine if dependency is already checked. table->put(...) returns 1988 // 'true' if the dependency is added (i.e., was not in the hashtable). 1989 if (table->put(*current_sig, 1)) { 1990 if (deps.check_dependency() != NULL) { 1991 // Dependency checking failed. Print out information about the failed 1992 // dependency and finally fail with an assert. We can fail here, since 1993 // dependency checking is never done in a product build. 1994 tty->print_cr("Failed dependency:"); 1995 changes.print(); 1996 nm->print(); 1997 nm->print_dependencies(); 1998 assert(false, "Should have been marked for deoptimization"); 1999 } 2000 } 2001 } 2002 } 2003 } 2004 } 2005 2006 bool nmethod::check_dependency_on(DepChange& changes) { 2007 // What has happened: 2008 // 1) a new class dependee has been added 2009 // 2) dependee and all its super classes have been marked 2010 bool found_check = false; // set true if we are upset 2011 for (Dependencies::DepStream deps(this); deps.next(); ) { 2012 // Evaluate only relevant dependencies. 2013 if (deps.spot_check_dependency_at(changes) != NULL) { 2014 found_check = true; 2015 NOT_DEBUG(break); 2016 } 2017 } 2018 return found_check; 2019 } 2020 2021 // Called from mark_for_deoptimization, when dependee is invalidated. 2022 bool nmethod::is_dependent_on_method(Method* dependee) { 2023 for (Dependencies::DepStream deps(this); deps.next(); ) { 2024 if (deps.type() != Dependencies::evol_method) 2025 continue; 2026 Method* method = deps.method_argument(0); 2027 if (method == dependee) return true; 2028 } 2029 return false; 2030 } 2031 2032 2033 bool nmethod::is_patchable_at(address instr_addr) { 2034 assert(insts_contains(instr_addr), "wrong nmethod used"); 2035 if (is_zombie()) { 2036 // a zombie may never be patched 2037 return false; 2038 } 2039 return true; 2040 } 2041 2042 2043 address nmethod::continuation_for_implicit_exception(address pc) { 2044 // Exception happened outside inline-cache check code => we are inside 2045 // an active nmethod => use cpc to determine a return address 2046 int exception_offset = pc - code_begin(); 2047 int cont_offset = ImplicitExceptionTable(this).at( exception_offset ); 2048 #ifdef ASSERT 2049 if (cont_offset == 0) { 2050 Thread* thread = Thread::current(); 2051 ResetNoHandleMark rnm; // Might be called from LEAF/QUICK ENTRY 2052 HandleMark hm(thread); 2053 ResourceMark rm(thread); 2054 CodeBlob* cb = CodeCache::find_blob(pc); 2055 assert(cb != NULL && cb == this, ""); 2056 ttyLocker ttyl; 2057 tty->print_cr("implicit exception happened at " INTPTR_FORMAT, p2i(pc)); 2058 print(); 2059 method()->print_codes(); 2060 print_code(); 2061 print_pcs(); 2062 } 2063 #endif 2064 if (cont_offset == 0) { 2065 // Let the normal error handling report the exception 2066 return NULL; 2067 } 2068 return code_begin() + cont_offset; 2069 } 2070 2071 2072 2073 void nmethod_init() { 2074 // make sure you didn't forget to adjust the filler fields 2075 assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word"); 2076 } 2077 2078 2079 //------------------------------------------------------------------------------------------- 2080 2081 2082 // QQQ might we make this work from a frame?? 2083 nmethodLocker::nmethodLocker(address pc) { 2084 CodeBlob* cb = CodeCache::find_blob(pc); 2085 guarantee(cb != NULL && cb->is_compiled(), "bad pc for a nmethod found"); 2086 _nm = cb->as_compiled_method(); 2087 lock_nmethod(_nm); 2088 } 2089 2090 // Only JvmtiDeferredEvent::compiled_method_unload_event() 2091 // should pass zombie_ok == true. 2092 void nmethodLocker::lock_nmethod(CompiledMethod* cm, bool zombie_ok) { 2093 if (cm == NULL) return; 2094 if (cm->is_aot()) return; // FIXME: Revisit once _lock_count is added to aot_method 2095 nmethod* nm = cm->as_nmethod(); 2096 Atomic::inc(&nm->_lock_count); 2097 assert(zombie_ok || !nm->is_zombie(), "cannot lock a zombie method: %p", nm); 2098 } 2099 2100 void nmethodLocker::unlock_nmethod(CompiledMethod* cm) { 2101 if (cm == NULL) return; 2102 if (cm->is_aot()) return; // FIXME: Revisit once _lock_count is added to aot_method 2103 nmethod* nm = cm->as_nmethod(); 2104 Atomic::dec(&nm->_lock_count); 2105 assert(nm->_lock_count >= 0, "unmatched nmethod lock/unlock"); 2106 } 2107 2108 2109 // ----------------------------------------------------------------------------- 2110 // Verification 2111 2112 class VerifyOopsClosure: public OopClosure { 2113 nmethod* _nm; 2114 bool _ok; 2115 public: 2116 VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { } 2117 bool ok() { return _ok; } 2118 virtual void do_oop(oop* p) { 2119 if (oopDesc::is_oop_or_null(*p)) return; 2120 if (_ok) { 2121 _nm->print_nmethod(true); 2122 _ok = false; 2123 } 2124 tty->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)", 2125 p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm)); 2126 } 2127 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); } 2128 }; 2129 2130 void nmethod::verify() { 2131 2132 // Hmm. OSR methods can be deopted but not marked as zombie or not_entrant 2133 // seems odd. 2134 2135 if (is_zombie() || is_not_entrant() || is_unloaded()) 2136 return; 2137 2138 // Make sure all the entry points are correctly aligned for patching. 2139 NativeJump::check_verified_entry_alignment(entry_point(), verified_entry_point()); 2140 2141 // assert(oopDesc::is_oop(method()), "must be valid"); 2142 2143 ResourceMark rm; 2144 2145 if (!CodeCache::contains(this)) { 2146 fatal("nmethod at " INTPTR_FORMAT " not in zone", p2i(this)); 2147 } 2148 2149 if(is_native_method() ) 2150 return; 2151 2152 nmethod* nm = CodeCache::find_nmethod(verified_entry_point()); 2153 if (nm != this) { 2154 fatal("findNMethod did not find this nmethod (" INTPTR_FORMAT ")", p2i(this)); 2155 } 2156 2157 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) { 2158 if (! p->verify(this)) { 2159 tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", p2i(this)); 2160 } 2161 } 2162 2163 VerifyOopsClosure voc(this); 2164 oops_do(&voc); 2165 assert(voc.ok(), "embedded oops must be OK"); 2166 Universe::heap()->verify_nmethod(this); 2167 2168 verify_scopes(); 2169 } 2170 2171 2172 void nmethod::verify_interrupt_point(address call_site) { 2173 // Verify IC only when nmethod installation is finished. 2174 if (!is_not_installed()) { 2175 if (CompiledICLocker::is_safe(this)) { 2176 CompiledIC_at(this, call_site); 2177 CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops()); 2178 } else { 2179 CompiledICLocker ml_verify(this); 2180 CompiledIC_at(this, call_site); 2181 } 2182 } 2183 2184 PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address()); 2185 assert(pd != NULL, "PcDesc must exist"); 2186 for (ScopeDesc* sd = new ScopeDesc(this, pd->scope_decode_offset(), 2187 pd->obj_decode_offset(), pd->should_reexecute(), pd->rethrow_exception(), 2188 pd->return_oop()); 2189 !sd->is_top(); sd = sd->sender()) { 2190 sd->verify(); 2191 } 2192 } 2193 2194 void nmethod::verify_scopes() { 2195 if( !method() ) return; // Runtime stubs have no scope 2196 if (method()->is_native()) return; // Ignore stub methods. 2197 // iterate through all interrupt point 2198 // and verify the debug information is valid. 2199 RelocIterator iter((nmethod*)this); 2200 while (iter.next()) { 2201 address stub = NULL; 2202 switch (iter.type()) { 2203 case relocInfo::virtual_call_type: 2204 verify_interrupt_point(iter.addr()); 2205 break; 2206 case relocInfo::opt_virtual_call_type: 2207 stub = iter.opt_virtual_call_reloc()->static_stub(false); 2208 verify_interrupt_point(iter.addr()); 2209 break; 2210 case relocInfo::static_call_type: 2211 stub = iter.static_call_reloc()->static_stub(false); 2212 //verify_interrupt_point(iter.addr()); 2213 break; 2214 case relocInfo::runtime_call_type: 2215 case relocInfo::runtime_call_w_cp_type: { 2216 address destination = iter.reloc()->value(); 2217 // Right now there is no way to find out which entries support 2218 // an interrupt point. It would be nice if we had this 2219 // information in a table. 2220 break; 2221 } 2222 default: 2223 break; 2224 } 2225 assert(stub == NULL || stub_contains(stub), "static call stub outside stub section"); 2226 } 2227 } 2228 2229 2230 // ----------------------------------------------------------------------------- 2231 // Printing operations 2232 2233 void nmethod::print() const { 2234 ResourceMark rm; 2235 ttyLocker ttyl; // keep the following output all in one block 2236 2237 tty->print("Compiled method "); 2238 2239 if (is_compiled_by_c1()) { 2240 tty->print("(c1) "); 2241 } else if (is_compiled_by_c2()) { 2242 tty->print("(c2) "); 2243 } else if (is_compiled_by_jvmci()) { 2244 tty->print("(JVMCI) "); 2245 } else { 2246 tty->print("(nm) "); 2247 } 2248 2249 print_on(tty, NULL); 2250 2251 if (WizardMode) { 2252 tty->print("((nmethod*) " INTPTR_FORMAT ") ", p2i(this)); 2253 tty->print(" for method " INTPTR_FORMAT , p2i(method())); 2254 tty->print(" { "); 2255 tty->print_cr("%s ", state()); 2256 tty->print_cr("}:"); 2257 } 2258 if (size () > 0) tty->print_cr(" total in heap [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2259 p2i(this), 2260 p2i(this) + size(), 2261 size()); 2262 if (relocation_size () > 0) tty->print_cr(" relocation [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2263 p2i(relocation_begin()), 2264 p2i(relocation_end()), 2265 relocation_size()); 2266 if (consts_size () > 0) tty->print_cr(" constants [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2267 p2i(consts_begin()), 2268 p2i(consts_end()), 2269 consts_size()); 2270 if (insts_size () > 0) tty->print_cr(" main code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2271 p2i(insts_begin()), 2272 p2i(insts_end()), 2273 insts_size()); 2274 if (stub_size () > 0) tty->print_cr(" stub code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2275 p2i(stub_begin()), 2276 p2i(stub_end()), 2277 stub_size()); 2278 if (oops_size () > 0) tty->print_cr(" oops [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2279 p2i(oops_begin()), 2280 p2i(oops_end()), 2281 oops_size()); 2282 if (metadata_size () > 0) tty->print_cr(" metadata [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2283 p2i(metadata_begin()), 2284 p2i(metadata_end()), 2285 metadata_size()); 2286 if (scopes_data_size () > 0) tty->print_cr(" scopes data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2287 p2i(scopes_data_begin()), 2288 p2i(scopes_data_end()), 2289 scopes_data_size()); 2290 if (scopes_pcs_size () > 0) tty->print_cr(" scopes pcs [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2291 p2i(scopes_pcs_begin()), 2292 p2i(scopes_pcs_end()), 2293 scopes_pcs_size()); 2294 if (dependencies_size () > 0) tty->print_cr(" dependencies [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2295 p2i(dependencies_begin()), 2296 p2i(dependencies_end()), 2297 dependencies_size()); 2298 if (handler_table_size() > 0) tty->print_cr(" handler table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2299 p2i(handler_table_begin()), 2300 p2i(handler_table_end()), 2301 handler_table_size()); 2302 if (nul_chk_table_size() > 0) tty->print_cr(" nul chk table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2303 p2i(nul_chk_table_begin()), 2304 p2i(nul_chk_table_end()), 2305 nul_chk_table_size()); 2306 #if INCLUDE_JVMCI 2307 if (speculations_size () > 0) tty->print_cr(" speculations [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2308 p2i(speculations_begin()), 2309 p2i(speculations_end()), 2310 speculations_size()); 2311 if (jvmci_data_size () > 0) tty->print_cr(" JVMCI data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2312 p2i(jvmci_data_begin()), 2313 p2i(jvmci_data_end()), 2314 jvmci_data_size()); 2315 #endif 2316 } 2317 2318 #ifndef PRODUCT 2319 2320 void nmethod::print_scopes() { 2321 // Find the first pc desc for all scopes in the code and print it. 2322 ResourceMark rm; 2323 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) { 2324 if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null) 2325 continue; 2326 2327 ScopeDesc* sd = scope_desc_at(p->real_pc(this)); 2328 while (sd != NULL) { 2329 sd->print_on(tty, p); 2330 sd = sd->sender(); 2331 } 2332 } 2333 } 2334 2335 void nmethod::print_dependencies() { 2336 ResourceMark rm; 2337 ttyLocker ttyl; // keep the following output all in one block 2338 tty->print_cr("Dependencies:"); 2339 for (Dependencies::DepStream deps(this); deps.next(); ) { 2340 deps.print_dependency(); 2341 Klass* ctxk = deps.context_type(); 2342 if (ctxk != NULL) { 2343 if (ctxk->is_instance_klass() && InstanceKlass::cast(ctxk)->is_dependent_nmethod(this)) { 2344 tty->print_cr(" [nmethod<=klass]%s", ctxk->external_name()); 2345 } 2346 } 2347 deps.log_dependency(); // put it into the xml log also 2348 } 2349 } 2350 2351 2352 void nmethod::print_relocations() { 2353 ResourceMark m; // in case methods get printed via the debugger 2354 tty->print_cr("relocations:"); 2355 RelocIterator iter(this); 2356 iter.print(); 2357 } 2358 2359 2360 void nmethod::print_pcs() { 2361 ResourceMark m; // in case methods get printed via debugger 2362 tty->print_cr("pc-bytecode offsets:"); 2363 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) { 2364 p->print(this); 2365 } 2366 } 2367 2368 void nmethod::print_recorded_oops() { 2369 tty->print_cr("Recorded oops:"); 2370 for (int i = 0; i < oops_count(); i++) { 2371 oop o = oop_at(i); 2372 tty->print("#%3d: " INTPTR_FORMAT " ", i, p2i(o)); 2373 if (o == Universe::non_oop_word()) { 2374 tty->print("non-oop word"); 2375 } else { 2376 if (o != NULL) { 2377 o->print_value(); 2378 } else { 2379 tty->print_cr("NULL"); 2380 } 2381 } 2382 tty->cr(); 2383 } 2384 } 2385 2386 void nmethod::print_recorded_metadata() { 2387 tty->print_cr("Recorded metadata:"); 2388 for (int i = 0; i < metadata_count(); i++) { 2389 Metadata* m = metadata_at(i); 2390 tty->print("#%3d: " INTPTR_FORMAT " ", i, p2i(m)); 2391 if (m == (Metadata*)Universe::non_oop_word()) { 2392 tty->print("non-metadata word"); 2393 } else { 2394 Metadata::print_value_on_maybe_null(tty, m); 2395 } 2396 tty->cr(); 2397 } 2398 } 2399 2400 #endif // PRODUCT 2401 2402 const char* nmethod::reloc_string_for(u_char* begin, u_char* end) { 2403 RelocIterator iter(this, begin, end); 2404 bool have_one = false; 2405 while (iter.next()) { 2406 have_one = true; 2407 switch (iter.type()) { 2408 case relocInfo::none: return "no_reloc"; 2409 case relocInfo::oop_type: { 2410 stringStream st; 2411 oop_Relocation* r = iter.oop_reloc(); 2412 oop obj = r->oop_value(); 2413 st.print("oop("); 2414 if (obj == NULL) st.print("NULL"); 2415 else obj->print_value_on(&st); 2416 st.print(")"); 2417 return st.as_string(); 2418 } 2419 case relocInfo::metadata_type: { 2420 stringStream st; 2421 metadata_Relocation* r = iter.metadata_reloc(); 2422 Metadata* obj = r->metadata_value(); 2423 st.print("metadata("); 2424 if (obj == NULL) st.print("NULL"); 2425 else obj->print_value_on(&st); 2426 st.print(")"); 2427 return st.as_string(); 2428 } 2429 case relocInfo::runtime_call_type: 2430 case relocInfo::runtime_call_w_cp_type: { 2431 stringStream st; 2432 st.print("runtime_call"); 2433 CallRelocation* r = (CallRelocation*)iter.reloc(); 2434 address dest = r->destination(); 2435 CodeBlob* cb = CodeCache::find_blob(dest); 2436 if (cb != NULL) { 2437 st.print(" %s", cb->name()); 2438 } else { 2439 ResourceMark rm; 2440 const int buflen = 1024; 2441 char* buf = NEW_RESOURCE_ARRAY(char, buflen); 2442 int offset; 2443 if (os::dll_address_to_function_name(dest, buf, buflen, &offset)) { 2444 st.print(" %s", buf); 2445 if (offset != 0) { 2446 st.print("+%d", offset); 2447 } 2448 } 2449 } 2450 return st.as_string(); 2451 } 2452 case relocInfo::virtual_call_type: { 2453 stringStream st; 2454 st.print_raw("virtual_call"); 2455 virtual_call_Relocation* r = iter.virtual_call_reloc(); 2456 Method* m = r->method_value(); 2457 if (m != NULL) { 2458 assert(m->is_method(), ""); 2459 m->print_short_name(&st); 2460 } 2461 return st.as_string(); 2462 } 2463 case relocInfo::opt_virtual_call_type: { 2464 stringStream st; 2465 st.print_raw("optimized virtual_call"); 2466 opt_virtual_call_Relocation* r = iter.opt_virtual_call_reloc(); 2467 Method* m = r->method_value(); 2468 if (m != NULL) { 2469 assert(m->is_method(), ""); 2470 m->print_short_name(&st); 2471 } 2472 return st.as_string(); 2473 } 2474 case relocInfo::static_call_type: { 2475 stringStream st; 2476 st.print_raw("static_call"); 2477 static_call_Relocation* r = iter.static_call_reloc(); 2478 Method* m = r->method_value(); 2479 if (m != NULL) { 2480 assert(m->is_method(), ""); 2481 m->print_short_name(&st); 2482 } 2483 return st.as_string(); 2484 } 2485 case relocInfo::static_stub_type: return "static_stub"; 2486 case relocInfo::external_word_type: return "external_word"; 2487 case relocInfo::internal_word_type: return "internal_word"; 2488 case relocInfo::section_word_type: return "section_word"; 2489 case relocInfo::poll_type: return "poll"; 2490 case relocInfo::poll_return_type: return "poll_return"; 2491 case relocInfo::trampoline_stub_type: return "trampoline_stub"; 2492 case relocInfo::type_mask: return "type_bit_mask"; 2493 2494 default: 2495 break; 2496 } 2497 } 2498 return have_one ? "other" : NULL; 2499 } 2500 2501 // Return a the last scope in (begin..end] 2502 ScopeDesc* nmethod::scope_desc_in(address begin, address end) { 2503 PcDesc* p = pc_desc_near(begin+1); 2504 if (p != NULL && p->real_pc(this) <= end) { 2505 return new ScopeDesc(this, p->scope_decode_offset(), 2506 p->obj_decode_offset(), p->should_reexecute(), p->rethrow_exception(), 2507 p->return_oop()); 2508 } 2509 return NULL; 2510 } 2511 2512 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin) const { 2513 if (block_begin == entry_point()) stream->print_cr("[Entry Point]"); 2514 if (block_begin == verified_entry_point()) stream->print_cr("[Verified Entry Point]"); 2515 if (JVMCI_ONLY(_exception_offset >= 0 &&) block_begin == exception_begin()) stream->print_cr("[Exception Handler]"); 2516 if (block_begin == stub_begin()) stream->print_cr("[Stub Code]"); 2517 if (JVMCI_ONLY(_deopt_handler_begin != NULL &&) block_begin == deopt_handler_begin()) stream->print_cr("[Deopt Handler Code]"); 2518 2519 if (has_method_handle_invokes()) 2520 if (block_begin == deopt_mh_handler_begin()) stream->print_cr("[Deopt MH Handler Code]"); 2521 2522 if (block_begin == consts_begin()) stream->print_cr("[Constants]"); 2523 2524 if (block_begin == entry_point()) { 2525 methodHandle m = method(); 2526 if (m.not_null()) { 2527 stream->print(" # "); 2528 m->print_value_on(stream); 2529 stream->cr(); 2530 } 2531 if (m.not_null() && !is_osr_method()) { 2532 ResourceMark rm; 2533 int sizeargs = m->size_of_parameters(); 2534 BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs); 2535 VMRegPair* regs = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs); 2536 { 2537 int sig_index = 0; 2538 if (!m->is_static()) 2539 sig_bt[sig_index++] = T_OBJECT; // 'this' 2540 for (SignatureStream ss(m->signature()); !ss.at_return_type(); ss.next()) { 2541 BasicType t = ss.type(); 2542 sig_bt[sig_index++] = t; 2543 if (type2size[t] == 2) { 2544 sig_bt[sig_index++] = T_VOID; 2545 } else { 2546 assert(type2size[t] == 1, "size is 1 or 2"); 2547 } 2548 } 2549 assert(sig_index == sizeargs, ""); 2550 } 2551 const char* spname = "sp"; // make arch-specific? 2552 intptr_t out_preserve = SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs, false); 2553 int stack_slot_offset = this->frame_size() * wordSize; 2554 int tab1 = 14, tab2 = 24; 2555 int sig_index = 0; 2556 int arg_index = (m->is_static() ? 0 : -1); 2557 bool did_old_sp = false; 2558 for (SignatureStream ss(m->signature()); !ss.at_return_type(); ) { 2559 bool at_this = (arg_index == -1); 2560 bool at_old_sp = false; 2561 BasicType t = (at_this ? T_OBJECT : ss.type()); 2562 assert(t == sig_bt[sig_index], "sigs in sync"); 2563 if (at_this) 2564 stream->print(" # this: "); 2565 else 2566 stream->print(" # parm%d: ", arg_index); 2567 stream->move_to(tab1); 2568 VMReg fst = regs[sig_index].first(); 2569 VMReg snd = regs[sig_index].second(); 2570 if (fst->is_reg()) { 2571 stream->print("%s", fst->name()); 2572 if (snd->is_valid()) { 2573 stream->print(":%s", snd->name()); 2574 } 2575 } else if (fst->is_stack()) { 2576 int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset; 2577 if (offset == stack_slot_offset) at_old_sp = true; 2578 stream->print("[%s+0x%x]", spname, offset); 2579 } else { 2580 stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd); 2581 } 2582 stream->print(" "); 2583 stream->move_to(tab2); 2584 stream->print("= "); 2585 if (at_this) { 2586 m->method_holder()->print_value_on(stream); 2587 } else { 2588 bool did_name = false; 2589 if (!at_this && ss.is_object()) { 2590 Symbol* name = ss.as_symbol_or_null(); 2591 if (name != NULL) { 2592 name->print_value_on(stream); 2593 did_name = true; 2594 } 2595 } 2596 if (!did_name) 2597 stream->print("%s", type2name(t)); 2598 } 2599 if (at_old_sp) { 2600 stream->print(" (%s of caller)", spname); 2601 did_old_sp = true; 2602 } 2603 stream->cr(); 2604 sig_index += type2size[t]; 2605 arg_index += 1; 2606 if (!at_this) ss.next(); 2607 } 2608 if (!did_old_sp) { 2609 stream->print(" # "); 2610 stream->move_to(tab1); 2611 stream->print("[%s+0x%x]", spname, stack_slot_offset); 2612 stream->print(" (%s of caller)", spname); 2613 stream->cr(); 2614 } 2615 } 2616 } 2617 } 2618 2619 void nmethod::print_code_comment_on(outputStream* st, int column, u_char* begin, u_char* end) { 2620 // First, find an oopmap in (begin, end]. 2621 // We use the odd half-closed interval so that oop maps and scope descs 2622 // which are tied to the byte after a call are printed with the call itself. 2623 address base = code_begin(); 2624 ImmutableOopMapSet* oms = oop_maps(); 2625 if (oms != NULL) { 2626 for (int i = 0, imax = oms->count(); i < imax; i++) { 2627 const ImmutableOopMapPair* pair = oms->pair_at(i); 2628 const ImmutableOopMap* om = pair->get_from(oms); 2629 address pc = base + pair->pc_offset(); 2630 if (pc > begin) { 2631 if (pc <= end) { 2632 st->move_to(column); 2633 st->print("; "); 2634 om->print_on(st); 2635 } 2636 break; 2637 } 2638 } 2639 } 2640 2641 // Print any debug info present at this pc. 2642 ScopeDesc* sd = scope_desc_in(begin, end); 2643 if (sd != NULL) { 2644 st->move_to(column); 2645 if (sd->bci() == SynchronizationEntryBCI) { 2646 st->print(";*synchronization entry"); 2647 } else if (sd->bci() == AfterBci) { 2648 st->print(";* method exit (unlocked if synchronized)"); 2649 } else if (sd->bci() == UnwindBci) { 2650 st->print(";* unwind (locked if synchronized)"); 2651 } else if (sd->bci() == AfterExceptionBci) { 2652 st->print(";* unwind (unlocked if synchronized)"); 2653 } else if (sd->bci() == UnknownBci) { 2654 st->print(";* unknown"); 2655 } else if (sd->bci() == InvalidFrameStateBci) { 2656 st->print(";* invalid frame state"); 2657 } else { 2658 if (sd->method() == NULL) { 2659 st->print("method is NULL"); 2660 } else if (sd->method()->is_native()) { 2661 st->print("method is native"); 2662 } else { 2663 Bytecodes::Code bc = sd->method()->java_code_at(sd->bci()); 2664 st->print(";*%s", Bytecodes::name(bc)); 2665 switch (bc) { 2666 case Bytecodes::_invokevirtual: 2667 case Bytecodes::_invokespecial: 2668 case Bytecodes::_invokestatic: 2669 case Bytecodes::_invokeinterface: 2670 { 2671 Bytecode_invoke invoke(sd->method(), sd->bci()); 2672 st->print(" "); 2673 if (invoke.name() != NULL) 2674 invoke.name()->print_symbol_on(st); 2675 else 2676 st->print("<UNKNOWN>"); 2677 break; 2678 } 2679 case Bytecodes::_getfield: 2680 case Bytecodes::_putfield: 2681 case Bytecodes::_getstatic: 2682 case Bytecodes::_putstatic: 2683 { 2684 Bytecode_field field(sd->method(), sd->bci()); 2685 st->print(" "); 2686 if (field.name() != NULL) 2687 field.name()->print_symbol_on(st); 2688 else 2689 st->print("<UNKNOWN>"); 2690 } 2691 default: 2692 break; 2693 } 2694 } 2695 st->print(" {reexecute=%d rethrow=%d return_oop=%d}", sd->should_reexecute(), sd->rethrow_exception(), sd->return_oop()); 2696 } 2697 2698 // Print all scopes 2699 for (;sd != NULL; sd = sd->sender()) { 2700 st->move_to(column); 2701 st->print("; -"); 2702 if (sd->method() == NULL) { 2703 st->print("method is NULL"); 2704 } else { 2705 sd->method()->print_short_name(st); 2706 } 2707 int lineno = sd->method()->line_number_from_bci(sd->bci()); 2708 if (lineno != -1) { 2709 st->print("@%d (line %d)", sd->bci(), lineno); 2710 } else { 2711 st->print("@%d", sd->bci()); 2712 } 2713 st->cr(); 2714 } 2715 } 2716 2717 // Print relocation information 2718 const char* str = reloc_string_for(begin, end); 2719 if (str != NULL) { 2720 if (sd != NULL) st->cr(); 2721 st->move_to(column); 2722 st->print("; {%s}", str); 2723 } 2724 int cont_offset = ImplicitExceptionTable(this).at(begin - code_begin()); 2725 if (cont_offset != 0) { 2726 st->move_to(column); 2727 st->print("; implicit exception: dispatches to " INTPTR_FORMAT, p2i(code_begin() + cont_offset)); 2728 } 2729 2730 } 2731 2732 class DirectNativeCallWrapper: public NativeCallWrapper { 2733 private: 2734 NativeCall* _call; 2735 2736 public: 2737 DirectNativeCallWrapper(NativeCall* call) : _call(call) {} 2738 2739 virtual address destination() const { return _call->destination(); } 2740 virtual address instruction_address() const { return _call->instruction_address(); } 2741 virtual address next_instruction_address() const { return _call->next_instruction_address(); } 2742 virtual address return_address() const { return _call->return_address(); } 2743 2744 virtual address get_resolve_call_stub(bool is_optimized) const { 2745 if (is_optimized) { 2746 return SharedRuntime::get_resolve_opt_virtual_call_stub(); 2747 } 2748 return SharedRuntime::get_resolve_virtual_call_stub(); 2749 } 2750 2751 virtual void set_destination_mt_safe(address dest) { 2752 #if INCLUDE_AOT 2753 if (UseAOT) { 2754 CodeBlob* callee = CodeCache::find_blob(dest); 2755 CompiledMethod* cm = callee->as_compiled_method_or_null(); 2756 if (cm != NULL && cm->is_far_code()) { 2757 // Temporary fix, see JDK-8143106 2758 CompiledDirectStaticCall* csc = CompiledDirectStaticCall::at(instruction_address()); 2759 csc->set_to_far(methodHandle(cm->method()), dest); 2760 return; 2761 } 2762 } 2763 #endif 2764 _call->set_destination_mt_safe(dest); 2765 } 2766 2767 virtual void set_to_interpreted(const methodHandle& method, CompiledICInfo& info) { 2768 CompiledDirectStaticCall* csc = CompiledDirectStaticCall::at(instruction_address()); 2769 #if INCLUDE_AOT 2770 if (info.to_aot()) { 2771 csc->set_to_far(method, info.entry()); 2772 } else 2773 #endif 2774 { 2775 csc->set_to_interpreted(method, info.entry()); 2776 } 2777 } 2778 2779 virtual void verify() const { 2780 // make sure code pattern is actually a call imm32 instruction 2781 _call->verify(); 2782 _call->verify_alignment(); 2783 } 2784 2785 virtual void verify_resolve_call(address dest) const { 2786 CodeBlob* db = CodeCache::find_blob_unsafe(dest); 2787 assert(db != NULL && !db->is_adapter_blob(), "must use stub!"); 2788 } 2789 2790 virtual bool is_call_to_interpreted(address dest) const { 2791 CodeBlob* cb = CodeCache::find_blob(_call->instruction_address()); 2792 return cb->contains(dest); 2793 } 2794 2795 virtual bool is_safe_for_patching() const { return false; } 2796 2797 virtual NativeInstruction* get_load_instruction(virtual_call_Relocation* r) const { 2798 return nativeMovConstReg_at(r->cached_value()); 2799 } 2800 2801 virtual void *get_data(NativeInstruction* instruction) const { 2802 return (void*)((NativeMovConstReg*) instruction)->data(); 2803 } 2804 2805 virtual void set_data(NativeInstruction* instruction, intptr_t data) { 2806 ((NativeMovConstReg*) instruction)->set_data(data); 2807 } 2808 }; 2809 2810 NativeCallWrapper* nmethod::call_wrapper_at(address call) const { 2811 return new DirectNativeCallWrapper((NativeCall*) call); 2812 } 2813 2814 NativeCallWrapper* nmethod::call_wrapper_before(address return_pc) const { 2815 return new DirectNativeCallWrapper(nativeCall_before(return_pc)); 2816 } 2817 2818 address nmethod::call_instruction_address(address pc) const { 2819 if (NativeCall::is_call_before(pc)) { 2820 NativeCall *ncall = nativeCall_before(pc); 2821 return ncall->instruction_address(); 2822 } 2823 return NULL; 2824 } 2825 2826 CompiledStaticCall* nmethod::compiledStaticCall_at(Relocation* call_site) const { 2827 return CompiledDirectStaticCall::at(call_site); 2828 } 2829 2830 CompiledStaticCall* nmethod::compiledStaticCall_at(address call_site) const { 2831 return CompiledDirectStaticCall::at(call_site); 2832 } 2833 2834 CompiledStaticCall* nmethod::compiledStaticCall_before(address return_addr) const { 2835 return CompiledDirectStaticCall::before(return_addr); 2836 } 2837 2838 #ifndef PRODUCT 2839 2840 void nmethod::print_value_on(outputStream* st) const { 2841 st->print("nmethod"); 2842 print_on(st, NULL); 2843 } 2844 2845 void nmethod::print_calls(outputStream* st) { 2846 RelocIterator iter(this); 2847 while (iter.next()) { 2848 switch (iter.type()) { 2849 case relocInfo::virtual_call_type: 2850 case relocInfo::opt_virtual_call_type: { 2851 CompiledICLocker ml_verify(this); 2852 CompiledIC_at(&iter)->print(); 2853 break; 2854 } 2855 case relocInfo::static_call_type: 2856 st->print_cr("Static call at " INTPTR_FORMAT, p2i(iter.reloc()->addr())); 2857 CompiledDirectStaticCall::at(iter.reloc())->print(); 2858 break; 2859 default: 2860 break; 2861 } 2862 } 2863 } 2864 2865 void nmethod::print_handler_table() { 2866 ExceptionHandlerTable(this).print(); 2867 } 2868 2869 void nmethod::print_nul_chk_table() { 2870 ImplicitExceptionTable(this).print(code_begin()); 2871 } 2872 2873 void nmethod::print_statistics() { 2874 ttyLocker ttyl; 2875 if (xtty != NULL) xtty->head("statistics type='nmethod'"); 2876 native_nmethod_stats.print_native_nmethod_stats(); 2877 #ifdef COMPILER1 2878 c1_java_nmethod_stats.print_nmethod_stats("C1"); 2879 #endif 2880 #ifdef COMPILER2 2881 c2_java_nmethod_stats.print_nmethod_stats("C2"); 2882 #endif 2883 #if INCLUDE_JVMCI 2884 jvmci_java_nmethod_stats.print_nmethod_stats("JVMCI"); 2885 #endif 2886 unknown_java_nmethod_stats.print_nmethod_stats("Unknown"); 2887 DebugInformationRecorder::print_statistics(); 2888 #ifndef PRODUCT 2889 pc_nmethod_stats.print_pc_stats(); 2890 #endif 2891 Dependencies::print_statistics(); 2892 if (xtty != NULL) xtty->tail("statistics"); 2893 } 2894 2895 #endif // !PRODUCT 2896 2897 #if INCLUDE_JVMCI 2898 void nmethod::update_speculation(JavaThread* thread) { 2899 jlong speculation = thread->pending_failed_speculation(); 2900 if (speculation != 0) { 2901 guarantee(jvmci_nmethod_data() != NULL, "failed speculation in nmethod without failed speculation list"); 2902 jvmci_nmethod_data()->add_failed_speculation(this, speculation); 2903 thread->set_pending_failed_speculation(0); 2904 } 2905 } 2906 2907 const char* nmethod::jvmci_name() { 2908 if (jvmci_nmethod_data() != NULL) { 2909 return jvmci_nmethod_data()->name(); 2910 } 2911 return NULL; 2912 } 2913 #endif