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 "memory/universe.hpp" 46 #include "oops/access.inline.hpp" 47 #include "oops/method.inline.hpp" 48 #include "oops/methodData.hpp" 49 #include "oops/oop.inline.hpp" 50 #include "prims/jvmtiImpl.hpp" 51 #include "runtime/atomic.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 if (_method != NULL) { 1124 // OSR methods point to the Method*, but the Method* does not 1125 // point back! 1126 if (_method->code() == this) { 1127 _method->clear_code(); // Break a cycle 1128 } 1129 } 1130 1131 // Make the class unloaded - i.e., change state and notify sweeper 1132 assert(SafepointSynchronize::is_at_safepoint() || Thread::current()->is_ConcurrentGC_thread(), 1133 "must be at safepoint"); 1134 1135 { 1136 // Clear ICStubs and release any CompiledICHolders. 1137 CompiledICLocker ml(this); 1138 clear_ic_callsites(); 1139 } 1140 1141 // Unregister must be done before the state change 1142 { 1143 MutexLocker ml(SafepointSynchronize::is_at_safepoint() ? NULL : CodeCache_lock, 1144 Mutex::_no_safepoint_check_flag); 1145 Universe::heap()->unregister_nmethod(this); 1146 } 1147 1148 // Clear the method of this dead nmethod 1149 set_method(NULL); 1150 1151 // Log the unloading. 1152 log_state_change(); 1153 1154 // The Method* is gone at this point 1155 assert(_method == NULL, "Tautology"); 1156 1157 set_osr_link(NULL); 1158 NMethodSweeper::report_state_change(this); 1159 1160 // The release is only needed for compile-time ordering, as accesses 1161 // into the nmethod after the store are not safe due to the sweeper 1162 // being allowed to free it when the store is observed, during 1163 // concurrent nmethod unloading. Therefore, there is no need for 1164 // acquire on the loader side. 1165 OrderAccess::release_store(&_state, (signed char)unloaded); 1166 1167 #if INCLUDE_JVMCI 1168 // Clear the link between this nmethod and a HotSpotNmethod mirror 1169 JVMCINMethodData* nmethod_data = jvmci_nmethod_data(); 1170 if (nmethod_data != NULL) { 1171 nmethod_data->invalidate_nmethod_mirror(this); 1172 nmethod_data->clear_nmethod_mirror(this); 1173 } 1174 #endif 1175 } 1176 1177 void nmethod::invalidate_osr_method() { 1178 assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod"); 1179 // Remove from list of active nmethods 1180 if (method() != NULL) { 1181 method()->method_holder()->remove_osr_nmethod(this); 1182 } 1183 } 1184 1185 void nmethod::log_state_change() const { 1186 if (LogCompilation) { 1187 if (xtty != NULL) { 1188 ttyLocker ttyl; // keep the following output all in one block 1189 if (_state == unloaded) { 1190 xtty->begin_elem("make_unloaded thread='" UINTX_FORMAT "'", 1191 os::current_thread_id()); 1192 } else { 1193 xtty->begin_elem("make_not_entrant thread='" UINTX_FORMAT "'%s", 1194 os::current_thread_id(), 1195 (_state == zombie ? " zombie='1'" : "")); 1196 } 1197 log_identity(xtty); 1198 xtty->stamp(); 1199 xtty->end_elem(); 1200 } 1201 } 1202 1203 const char *state_msg = _state == zombie ? "made zombie" : "made not entrant"; 1204 CompileTask::print_ul(this, state_msg); 1205 if (PrintCompilation && _state != unloaded) { 1206 print_on(tty, state_msg); 1207 } 1208 } 1209 1210 void nmethod::unlink_from_method(bool acquire_lock) { 1211 // We need to check if both the _code and _from_compiled_code_entry_point 1212 // refer to this nmethod because there is a race in setting these two fields 1213 // in Method* as seen in bugid 4947125. 1214 // If the vep() points to the zombie nmethod, the memory for the nmethod 1215 // could be flushed and the compiler and vtable stubs could still call 1216 // through it. 1217 if (method() != NULL && (method()->code() == this || 1218 method()->from_compiled_entry() == verified_entry_point())) { 1219 method()->clear_code(acquire_lock); 1220 } 1221 } 1222 1223 /** 1224 * Common functionality for both make_not_entrant and make_zombie 1225 */ 1226 bool nmethod::make_not_entrant_or_zombie(int state) { 1227 assert(state == zombie || state == not_entrant, "must be zombie or not_entrant"); 1228 assert(!is_zombie(), "should not already be a zombie"); 1229 1230 if (_state == state) { 1231 // Avoid taking the lock if already in required state. 1232 // This is safe from races because the state is an end-state, 1233 // which the nmethod cannot back out of once entered. 1234 // No need for fencing either. 1235 return false; 1236 } 1237 1238 // Make sure neither the nmethod nor the method is flushed in case of a safepoint in code below. 1239 nmethodLocker nml(this); 1240 methodHandle the_method(method()); 1241 // This can be called while the system is already at a safepoint which is ok 1242 NoSafepointVerifier nsv(true, !SafepointSynchronize::is_at_safepoint()); 1243 1244 // during patching, depending on the nmethod state we must notify the GC that 1245 // code has been unloaded, unregistering it. We cannot do this right while 1246 // holding the Patching_lock because we need to use the CodeCache_lock. This 1247 // would be prone to deadlocks. 1248 // This flag is used to remember whether we need to later lock and unregister. 1249 bool nmethod_needs_unregister = false; 1250 1251 { 1252 // invalidate osr nmethod before acquiring the patching lock since 1253 // they both acquire leaf locks and we don't want a deadlock. 1254 // This logic is equivalent to the logic below for patching the 1255 // verified entry point of regular methods. We check that the 1256 // nmethod is in use to ensure that it is invalidated only once. 1257 if (is_osr_method() && is_in_use()) { 1258 // this effectively makes the osr nmethod not entrant 1259 invalidate_osr_method(); 1260 } 1261 1262 // Enter critical section. Does not block for safepoint. 1263 MutexLocker pl(Patching_lock, Mutex::_no_safepoint_check_flag); 1264 1265 if (_state == state) { 1266 // another thread already performed this transition so nothing 1267 // to do, but return false to indicate this. 1268 return false; 1269 } 1270 1271 // The caller can be calling the method statically or through an inline 1272 // cache call. 1273 if (!is_osr_method() && !is_not_entrant()) { 1274 NativeJump::patch_verified_entry(entry_point(), verified_entry_point(), 1275 SharedRuntime::get_handle_wrong_method_stub()); 1276 } 1277 1278 if (is_in_use() && update_recompile_counts()) { 1279 // It's a true state change, so mark the method as decompiled. 1280 // Do it only for transition from alive. 1281 inc_decompile_count(); 1282 } 1283 1284 // If the state is becoming a zombie, signal to unregister the nmethod with 1285 // the heap. 1286 // This nmethod may have already been unloaded during a full GC. 1287 if ((state == zombie) && !is_unloaded()) { 1288 nmethod_needs_unregister = true; 1289 } 1290 1291 // Must happen before state change. Otherwise we have a race condition in 1292 // nmethod::can_not_entrant_be_converted(). I.e., a method can immediately 1293 // transition its state from 'not_entrant' to 'zombie' without having to wait 1294 // for stack scanning. 1295 if (state == not_entrant) { 1296 mark_as_seen_on_stack(); 1297 OrderAccess::storestore(); // _stack_traversal_mark and _state 1298 } 1299 1300 // Change state 1301 _state = state; 1302 1303 // Log the transition once 1304 log_state_change(); 1305 1306 // Remove nmethod from method. 1307 unlink_from_method(false /* already owns Patching_lock */); 1308 } // leave critical region under Patching_lock 1309 1310 #if INCLUDE_JVMCI 1311 // Invalidate can't occur while holding the Patching lock 1312 JVMCINMethodData* nmethod_data = jvmci_nmethod_data(); 1313 if (nmethod_data != NULL) { 1314 nmethod_data->invalidate_nmethod_mirror(this); 1315 } 1316 #endif 1317 1318 #ifdef ASSERT 1319 if (is_osr_method() && method() != NULL) { 1320 // Make sure osr nmethod is invalidated, i.e. not on the list 1321 bool found = method()->method_holder()->remove_osr_nmethod(this); 1322 assert(!found, "osr nmethod should have been invalidated"); 1323 } 1324 #endif 1325 1326 // When the nmethod becomes zombie it is no longer alive so the 1327 // dependencies must be flushed. nmethods in the not_entrant 1328 // state will be flushed later when the transition to zombie 1329 // happens or they get unloaded. 1330 if (state == zombie) { 1331 { 1332 // Flushing dependencies must be done before any possible 1333 // safepoint can sneak in, otherwise the oops used by the 1334 // dependency logic could have become stale. 1335 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1336 if (nmethod_needs_unregister) { 1337 Universe::heap()->unregister_nmethod(this); 1338 } 1339 flush_dependencies(/*delete_immediately*/true); 1340 } 1341 1342 #if INCLUDE_JVMCI 1343 // Now that the nmethod has been unregistered, it's 1344 // safe to clear the HotSpotNmethod mirror oop. 1345 if (nmethod_data != NULL) { 1346 nmethod_data->clear_nmethod_mirror(this); 1347 } 1348 #endif 1349 1350 // Clear ICStubs to prevent back patching stubs of zombie or flushed 1351 // nmethods during the next safepoint (see ICStub::finalize), as well 1352 // as to free up CompiledICHolder resources. 1353 { 1354 CompiledICLocker ml(this); 1355 clear_ic_callsites(); 1356 } 1357 1358 // zombie only - if a JVMTI agent has enabled the CompiledMethodUnload 1359 // event and it hasn't already been reported for this nmethod then 1360 // report it now. The event may have been reported earlier if the GC 1361 // marked it for unloading). JvmtiDeferredEventQueue support means 1362 // we no longer go to a safepoint here. 1363 post_compiled_method_unload(); 1364 1365 #ifdef ASSERT 1366 // It's no longer safe to access the oops section since zombie 1367 // nmethods aren't scanned for GC. 1368 _oops_are_stale = true; 1369 #endif 1370 // the Method may be reclaimed by class unloading now that the 1371 // nmethod is in zombie state 1372 set_method(NULL); 1373 } else { 1374 assert(state == not_entrant, "other cases may need to be handled differently"); 1375 } 1376 1377 if (TraceCreateZombies && state == zombie) { 1378 ResourceMark m; 1379 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"); 1380 } 1381 1382 NMethodSweeper::report_state_change(this); 1383 return true; 1384 } 1385 1386 void nmethod::flush() { 1387 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1388 // Note that there are no valid oops in the nmethod anymore. 1389 assert(!is_osr_method() || is_unloaded() || is_zombie(), 1390 "osr nmethod must be unloaded or zombie before flushing"); 1391 assert(is_zombie() || is_osr_method(), "must be a zombie method"); 1392 assert (!is_locked_by_vm(), "locked methods shouldn't be flushed"); 1393 assert_locked_or_safepoint(CodeCache_lock); 1394 1395 // completely deallocate this method 1396 Events::log(JavaThread::current(), "flushing nmethod " INTPTR_FORMAT, p2i(this)); 1397 if (PrintMethodFlushing) { 1398 tty->print_cr("*flushing %s nmethod %3d/" INTPTR_FORMAT ". Live blobs:" UINT32_FORMAT 1399 "/Free CodeCache:" SIZE_FORMAT "Kb", 1400 is_osr_method() ? "osr" : "",_compile_id, p2i(this), CodeCache::blob_count(), 1401 CodeCache::unallocated_capacity(CodeCache::get_code_blob_type(this))/1024); 1402 } 1403 1404 // We need to deallocate any ExceptionCache data. 1405 // Note that we do not need to grab the nmethod lock for this, it 1406 // better be thread safe if we're disposing of it! 1407 ExceptionCache* ec = exception_cache(); 1408 set_exception_cache(NULL); 1409 while(ec != NULL) { 1410 ExceptionCache* next = ec->next(); 1411 delete ec; 1412 ec = next; 1413 } 1414 1415 Universe::heap()->flush_nmethod(this); 1416 CodeCache::unregister_old_nmethod(this); 1417 1418 CodeBlob::flush(); 1419 CodeCache::free(this); 1420 } 1421 1422 oop nmethod::oop_at(int index) const { 1423 if (index == 0) { 1424 return NULL; 1425 } 1426 return NativeAccess<AS_NO_KEEPALIVE>::oop_load(oop_addr_at(index)); 1427 } 1428 1429 // 1430 // Notify all classes this nmethod is dependent on that it is no 1431 // longer dependent. This should only be called in two situations. 1432 // First, when a nmethod transitions to a zombie all dependents need 1433 // to be clear. Since zombification happens at a safepoint there's no 1434 // synchronization issues. The second place is a little more tricky. 1435 // During phase 1 of mark sweep class unloading may happen and as a 1436 // result some nmethods may get unloaded. In this case the flushing 1437 // of dependencies must happen during phase 1 since after GC any 1438 // dependencies in the unloaded nmethod won't be updated, so 1439 // traversing the dependency information in unsafe. In that case this 1440 // function is called with a boolean argument and this function only 1441 // notifies instanceKlasses that are reachable 1442 1443 void nmethod::flush_dependencies(bool delete_immediately) { 1444 DEBUG_ONLY(bool called_by_gc = Universe::heap()->is_gc_active() || Thread::current()->is_ConcurrentGC_thread();) 1445 assert(called_by_gc != delete_immediately, 1446 "delete_immediately is false if and only if we are called during GC"); 1447 if (!has_flushed_dependencies()) { 1448 set_has_flushed_dependencies(); 1449 for (Dependencies::DepStream deps(this); deps.next(); ) { 1450 if (deps.type() == Dependencies::call_site_target_value) { 1451 // CallSite dependencies are managed on per-CallSite instance basis. 1452 oop call_site = deps.argument_oop(0); 1453 if (delete_immediately) { 1454 assert_locked_or_safepoint(CodeCache_lock); 1455 MethodHandles::remove_dependent_nmethod(call_site, this); 1456 } else { 1457 MethodHandles::clean_dependency_context(call_site); 1458 } 1459 } else { 1460 Klass* klass = deps.context_type(); 1461 if (klass == NULL) { 1462 continue; // ignore things like evol_method 1463 } 1464 // During GC delete_immediately is false, and liveness 1465 // of dependee determines class that needs to be updated. 1466 if (delete_immediately) { 1467 assert_locked_or_safepoint(CodeCache_lock); 1468 InstanceKlass::cast(klass)->remove_dependent_nmethod(this); 1469 } else if (klass->is_loader_alive()) { 1470 // The GC may clean dependency contexts concurrently and in parallel. 1471 InstanceKlass::cast(klass)->clean_dependency_context(); 1472 } 1473 } 1474 } 1475 } 1476 } 1477 1478 // ------------------------------------------------------------------ 1479 // post_compiled_method_load_event 1480 // new method for install_code() path 1481 // Transfer information from compilation to jvmti 1482 void nmethod::post_compiled_method_load_event() { 1483 1484 Method* moop = method(); 1485 HOTSPOT_COMPILED_METHOD_LOAD( 1486 (char *) moop->klass_name()->bytes(), 1487 moop->klass_name()->utf8_length(), 1488 (char *) moop->name()->bytes(), 1489 moop->name()->utf8_length(), 1490 (char *) moop->signature()->bytes(), 1491 moop->signature()->utf8_length(), 1492 insts_begin(), insts_size()); 1493 1494 if (JvmtiExport::should_post_compiled_method_load() || 1495 JvmtiExport::should_post_compiled_method_unload()) { 1496 get_and_cache_jmethod_id(); 1497 } 1498 1499 if (JvmtiExport::should_post_compiled_method_load()) { 1500 // Let the Service thread (which is a real Java thread) post the event 1501 MutexLocker ml(Service_lock, Mutex::_no_safepoint_check_flag); 1502 JvmtiDeferredEventQueue::enqueue( 1503 JvmtiDeferredEvent::compiled_method_load_event(this)); 1504 } 1505 } 1506 1507 jmethodID nmethod::get_and_cache_jmethod_id() { 1508 if (_jmethod_id == NULL) { 1509 // Cache the jmethod_id since it can no longer be looked up once the 1510 // method itself has been marked for unloading. 1511 _jmethod_id = method()->jmethod_id(); 1512 } 1513 return _jmethod_id; 1514 } 1515 1516 void nmethod::post_compiled_method_unload() { 1517 if (unload_reported()) { 1518 // During unloading we transition to unloaded and then to zombie 1519 // and the unloading is reported during the first transition. 1520 return; 1521 } 1522 1523 assert(_method != NULL && !is_unloaded(), "just checking"); 1524 DTRACE_METHOD_UNLOAD_PROBE(method()); 1525 1526 // If a JVMTI agent has enabled the CompiledMethodUnload event then 1527 // post the event. Sometime later this nmethod will be made a zombie 1528 // by the sweeper but the Method* will not be valid at that point. 1529 // If the _jmethod_id is null then no load event was ever requested 1530 // so don't bother posting the unload. The main reason for this is 1531 // that the jmethodID is a weak reference to the Method* so if 1532 // it's being unloaded there's no way to look it up since the weak 1533 // ref will have been cleared. 1534 if (_jmethod_id != NULL && JvmtiExport::should_post_compiled_method_unload()) { 1535 assert(!unload_reported(), "already unloaded"); 1536 JvmtiDeferredEvent event = 1537 JvmtiDeferredEvent::compiled_method_unload_event(this, 1538 _jmethod_id, insts_begin()); 1539 MutexLocker ml(Service_lock, Mutex::_no_safepoint_check_flag); 1540 JvmtiDeferredEventQueue::enqueue(event); 1541 } 1542 1543 // The JVMTI CompiledMethodUnload event can be enabled or disabled at 1544 // any time. As the nmethod is being unloaded now we mark it has 1545 // having the unload event reported - this will ensure that we don't 1546 // attempt to report the event in the unlikely scenario where the 1547 // event is enabled at the time the nmethod is made a zombie. 1548 set_unload_reported(); 1549 } 1550 1551 // Iterate over metadata calling this function. Used by RedefineClasses 1552 void nmethod::metadata_do(MetadataClosure* f) { 1553 { 1554 // Visit all immediate references that are embedded in the instruction stream. 1555 RelocIterator iter(this, oops_reloc_begin()); 1556 while (iter.next()) { 1557 if (iter.type() == relocInfo::metadata_type) { 1558 metadata_Relocation* r = iter.metadata_reloc(); 1559 // In this metadata, we must only follow those metadatas directly embedded in 1560 // the code. Other metadatas (oop_index>0) are seen as part of 1561 // the metadata section below. 1562 assert(1 == (r->metadata_is_immediate()) + 1563 (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()), 1564 "metadata must be found in exactly one place"); 1565 if (r->metadata_is_immediate() && r->metadata_value() != NULL) { 1566 Metadata* md = r->metadata_value(); 1567 if (md != _method) f->do_metadata(md); 1568 } 1569 } else if (iter.type() == relocInfo::virtual_call_type) { 1570 // Check compiledIC holders associated with this nmethod 1571 ResourceMark rm; 1572 CompiledIC *ic = CompiledIC_at(&iter); 1573 if (ic->is_icholder_call()) { 1574 CompiledICHolder* cichk = ic->cached_icholder(); 1575 f->do_metadata(cichk->holder_metadata()); 1576 f->do_metadata(cichk->holder_klass()); 1577 } else { 1578 Metadata* ic_oop = ic->cached_metadata(); 1579 if (ic_oop != NULL) { 1580 f->do_metadata(ic_oop); 1581 } 1582 } 1583 } 1584 } 1585 } 1586 1587 // Visit the metadata section 1588 for (Metadata** p = metadata_begin(); p < metadata_end(); p++) { 1589 if (*p == Universe::non_oop_word() || *p == NULL) continue; // skip non-oops 1590 Metadata* md = *p; 1591 f->do_metadata(md); 1592 } 1593 1594 // Visit metadata not embedded in the other places. 1595 if (_method != NULL) f->do_metadata(_method); 1596 } 1597 1598 // The _is_unloading_state encodes a tuple comprising the unloading cycle 1599 // and the result of IsUnloadingBehaviour::is_unloading() fpr that cycle. 1600 // This is the bit layout of the _is_unloading_state byte: 00000CCU 1601 // CC refers to the cycle, which has 2 bits, and U refers to the result of 1602 // IsUnloadingBehaviour::is_unloading() for that unloading cycle. 1603 1604 class IsUnloadingState: public AllStatic { 1605 static const uint8_t _is_unloading_mask = 1; 1606 static const uint8_t _is_unloading_shift = 0; 1607 static const uint8_t _unloading_cycle_mask = 6; 1608 static const uint8_t _unloading_cycle_shift = 1; 1609 1610 static uint8_t set_is_unloading(uint8_t state, bool value) { 1611 state &= ~_is_unloading_mask; 1612 if (value) { 1613 state |= 1 << _is_unloading_shift; 1614 } 1615 assert(is_unloading(state) == value, "unexpected unloading cycle overflow"); 1616 return state; 1617 } 1618 1619 static uint8_t set_unloading_cycle(uint8_t state, uint8_t value) { 1620 state &= ~_unloading_cycle_mask; 1621 state |= value << _unloading_cycle_shift; 1622 assert(unloading_cycle(state) == value, "unexpected unloading cycle overflow"); 1623 return state; 1624 } 1625 1626 public: 1627 static bool is_unloading(uint8_t state) { return (state & _is_unloading_mask) >> _is_unloading_shift == 1; } 1628 static uint8_t unloading_cycle(uint8_t state) { return (state & _unloading_cycle_mask) >> _unloading_cycle_shift; } 1629 1630 static uint8_t create(bool is_unloading, uint8_t unloading_cycle) { 1631 uint8_t state = 0; 1632 state = set_is_unloading(state, is_unloading); 1633 state = set_unloading_cycle(state, unloading_cycle); 1634 return state; 1635 } 1636 }; 1637 1638 bool nmethod::is_unloading() { 1639 uint8_t state = RawAccess<MO_RELAXED>::load(&_is_unloading_state); 1640 bool state_is_unloading = IsUnloadingState::is_unloading(state); 1641 uint8_t state_unloading_cycle = IsUnloadingState::unloading_cycle(state); 1642 if (state_is_unloading) { 1643 return true; 1644 } 1645 uint8_t current_cycle = CodeCache::unloading_cycle(); 1646 if (state_unloading_cycle == current_cycle) { 1647 return false; 1648 } 1649 1650 // The IsUnloadingBehaviour is responsible for checking if there are any dead 1651 // oops in the CompiledMethod, by calling oops_do on it. 1652 state_unloading_cycle = current_cycle; 1653 1654 if (is_zombie()) { 1655 // Zombies without calculated unloading epoch are never unloading due to GC. 1656 1657 // There are no races where a previously observed is_unloading() nmethod 1658 // suddenly becomes not is_unloading() due to here being observed as zombie. 1659 1660 // With STW unloading, all is_alive() && is_unloading() nmethods are unlinked 1661 // and unloaded in the safepoint. That makes races where an nmethod is first 1662 // observed as is_alive() && is_unloading() and subsequently observed as 1663 // is_zombie() impossible. 1664 1665 // With concurrent unloading, all references to is_unloading() nmethods are 1666 // first unlinked (e.g. IC caches and dependency contexts). Then a global 1667 // handshake operation is performed with all JavaThreads before finally 1668 // unloading the nmethods. The sweeper never converts is_alive() && is_unloading() 1669 // nmethods to zombies; it waits for them to become is_unloaded(). So before 1670 // the global handshake, it is impossible for is_unloading() nmethods to 1671 // racingly become is_zombie(). And is_unloading() is calculated for all is_alive() 1672 // nmethods before taking that global handshake, meaning that it will never 1673 // be recalculated after the handshake. 1674 1675 // After that global handshake, is_unloading() nmethods are only observable 1676 // to the iterators, and they will never trigger recomputation of the cached 1677 // is_unloading_state, and hence may not suffer from such races. 1678 1679 state_is_unloading = false; 1680 } else { 1681 state_is_unloading = IsUnloadingBehaviour::current()->is_unloading(this); 1682 } 1683 1684 state = IsUnloadingState::create(state_is_unloading, state_unloading_cycle); 1685 1686 RawAccess<MO_RELAXED>::store(&_is_unloading_state, state); 1687 1688 return state_is_unloading; 1689 } 1690 1691 void nmethod::clear_unloading_state() { 1692 uint8_t state = IsUnloadingState::create(false, CodeCache::unloading_cycle()); 1693 RawAccess<MO_RELAXED>::store(&_is_unloading_state, state); 1694 } 1695 1696 1697 // This is called at the end of the strong tracing/marking phase of a 1698 // GC to unload an nmethod if it contains otherwise unreachable 1699 // oops. 1700 1701 void nmethod::do_unloading(bool unloading_occurred) { 1702 // Make sure the oop's ready to receive visitors 1703 assert(!is_zombie() && !is_unloaded(), 1704 "should not call follow on zombie or unloaded nmethod"); 1705 1706 if (is_unloading()) { 1707 make_unloaded(); 1708 } else { 1709 guarantee(unload_nmethod_caches(unloading_occurred), 1710 "Should not need transition stubs"); 1711 } 1712 } 1713 1714 void nmethod::oops_do(OopClosure* f, bool allow_zombie) { 1715 // make sure the oops ready to receive visitors 1716 assert(allow_zombie || !is_zombie(), "should not call follow on zombie nmethod"); 1717 assert(!is_unloaded(), "should not call follow on unloaded nmethod"); 1718 1719 // Prevent extra code cache walk for platforms that don't have immediate oops. 1720 if (relocInfo::mustIterateImmediateOopsInCode()) { 1721 RelocIterator iter(this, oops_reloc_begin()); 1722 1723 while (iter.next()) { 1724 if (iter.type() == relocInfo::oop_type ) { 1725 oop_Relocation* r = iter.oop_reloc(); 1726 // In this loop, we must only follow those oops directly embedded in 1727 // the code. Other oops (oop_index>0) are seen as part of scopes_oops. 1728 assert(1 == (r->oop_is_immediate()) + 1729 (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()), 1730 "oop must be found in exactly one place"); 1731 if (r->oop_is_immediate() && r->oop_value() != NULL) { 1732 f->do_oop(r->oop_addr()); 1733 } 1734 } 1735 } 1736 } 1737 1738 // Scopes 1739 // This includes oop constants not inlined in the code stream. 1740 for (oop* p = oops_begin(); p < oops_end(); p++) { 1741 if (*p == Universe::non_oop_word()) continue; // skip non-oops 1742 f->do_oop(p); 1743 } 1744 } 1745 1746 #define NMETHOD_SENTINEL ((nmethod*)badAddress) 1747 1748 nmethod* volatile nmethod::_oops_do_mark_nmethods; 1749 1750 // An nmethod is "marked" if its _mark_link is set non-null. 1751 // Even if it is the end of the linked list, it will have a non-null link value, 1752 // as long as it is on the list. 1753 // This code must be MP safe, because it is used from parallel GC passes. 1754 bool nmethod::test_set_oops_do_mark() { 1755 assert(nmethod::oops_do_marking_is_active(), "oops_do_marking_prologue must be called"); 1756 if (_oops_do_mark_link == NULL) { 1757 // Claim this nmethod for this thread to mark. 1758 if (Atomic::replace_if_null(NMETHOD_SENTINEL, &_oops_do_mark_link)) { 1759 // Atomically append this nmethod (now claimed) to the head of the list: 1760 nmethod* observed_mark_nmethods = _oops_do_mark_nmethods; 1761 for (;;) { 1762 nmethod* required_mark_nmethods = observed_mark_nmethods; 1763 _oops_do_mark_link = required_mark_nmethods; 1764 observed_mark_nmethods = 1765 Atomic::cmpxchg(this, &_oops_do_mark_nmethods, required_mark_nmethods); 1766 if (observed_mark_nmethods == required_mark_nmethods) 1767 break; 1768 } 1769 // Mark was clear when we first saw this guy. 1770 LogTarget(Trace, gc, nmethod) lt; 1771 if (lt.is_enabled()) { 1772 LogStream ls(lt); 1773 CompileTask::print(&ls, this, "oops_do, mark", /*short_form:*/ true); 1774 } 1775 return false; 1776 } 1777 } 1778 // On fall through, another racing thread marked this nmethod before we did. 1779 return true; 1780 } 1781 1782 void nmethod::oops_do_marking_prologue() { 1783 log_trace(gc, nmethod)("oops_do_marking_prologue"); 1784 assert(_oops_do_mark_nmethods == NULL, "must not call oops_do_marking_prologue twice in a row"); 1785 // We use cmpxchg instead of regular assignment here because the user 1786 // may fork a bunch of threads, and we need them all to see the same state. 1787 nmethod* observed = Atomic::cmpxchg(NMETHOD_SENTINEL, &_oops_do_mark_nmethods, (nmethod*)NULL); 1788 guarantee(observed == NULL, "no races in this sequential code"); 1789 } 1790 1791 void nmethod::oops_do_marking_epilogue() { 1792 assert(_oops_do_mark_nmethods != NULL, "must not call oops_do_marking_epilogue twice in a row"); 1793 nmethod* cur = _oops_do_mark_nmethods; 1794 while (cur != NMETHOD_SENTINEL) { 1795 assert(cur != NULL, "not NULL-terminated"); 1796 nmethod* next = cur->_oops_do_mark_link; 1797 cur->_oops_do_mark_link = NULL; 1798 DEBUG_ONLY(cur->verify_oop_relocations()); 1799 1800 LogTarget(Trace, gc, nmethod) lt; 1801 if (lt.is_enabled()) { 1802 LogStream ls(lt); 1803 CompileTask::print(&ls, cur, "oops_do, unmark", /*short_form:*/ true); 1804 } 1805 cur = next; 1806 } 1807 nmethod* required = _oops_do_mark_nmethods; 1808 nmethod* observed = Atomic::cmpxchg((nmethod*)NULL, &_oops_do_mark_nmethods, required); 1809 guarantee(observed == required, "no races in this sequential code"); 1810 log_trace(gc, nmethod)("oops_do_marking_epilogue"); 1811 } 1812 1813 inline bool includes(void* p, void* from, void* to) { 1814 return from <= p && p < to; 1815 } 1816 1817 1818 void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) { 1819 assert(count >= 2, "must be sentinel values, at least"); 1820 1821 #ifdef ASSERT 1822 // must be sorted and unique; we do a binary search in find_pc_desc() 1823 int prev_offset = pcs[0].pc_offset(); 1824 assert(prev_offset == PcDesc::lower_offset_limit, 1825 "must start with a sentinel"); 1826 for (int i = 1; i < count; i++) { 1827 int this_offset = pcs[i].pc_offset(); 1828 assert(this_offset > prev_offset, "offsets must be sorted"); 1829 prev_offset = this_offset; 1830 } 1831 assert(prev_offset == PcDesc::upper_offset_limit, 1832 "must end with a sentinel"); 1833 #endif //ASSERT 1834 1835 // Search for MethodHandle invokes and tag the nmethod. 1836 for (int i = 0; i < count; i++) { 1837 if (pcs[i].is_method_handle_invoke()) { 1838 set_has_method_handle_invokes(true); 1839 break; 1840 } 1841 } 1842 assert(has_method_handle_invokes() == (_deopt_mh_handler_begin != NULL), "must have deopt mh handler"); 1843 1844 int size = count * sizeof(PcDesc); 1845 assert(scopes_pcs_size() >= size, "oob"); 1846 memcpy(scopes_pcs_begin(), pcs, size); 1847 1848 // Adjust the final sentinel downward. 1849 PcDesc* last_pc = &scopes_pcs_begin()[count-1]; 1850 assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity"); 1851 last_pc->set_pc_offset(content_size() + 1); 1852 for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) { 1853 // Fill any rounding gaps with copies of the last record. 1854 last_pc[1] = last_pc[0]; 1855 } 1856 // The following assert could fail if sizeof(PcDesc) is not 1857 // an integral multiple of oopSize (the rounding term). 1858 // If it fails, change the logic to always allocate a multiple 1859 // of sizeof(PcDesc), and fill unused words with copies of *last_pc. 1860 assert(last_pc + 1 == scopes_pcs_end(), "must match exactly"); 1861 } 1862 1863 void nmethod::copy_scopes_data(u_char* buffer, int size) { 1864 assert(scopes_data_size() >= size, "oob"); 1865 memcpy(scopes_data_begin(), buffer, size); 1866 } 1867 1868 #ifdef ASSERT 1869 static PcDesc* linear_search(const PcDescSearch& search, int pc_offset, bool approximate) { 1870 PcDesc* lower = search.scopes_pcs_begin(); 1871 PcDesc* upper = search.scopes_pcs_end(); 1872 lower += 1; // exclude initial sentinel 1873 PcDesc* res = NULL; 1874 for (PcDesc* p = lower; p < upper; p++) { 1875 NOT_PRODUCT(--pc_nmethod_stats.pc_desc_tests); // don't count this call to match_desc 1876 if (match_desc(p, pc_offset, approximate)) { 1877 if (res == NULL) 1878 res = p; 1879 else 1880 res = (PcDesc*) badAddress; 1881 } 1882 } 1883 return res; 1884 } 1885 #endif 1886 1887 1888 // Finds a PcDesc with real-pc equal to "pc" 1889 PcDesc* PcDescContainer::find_pc_desc_internal(address pc, bool approximate, const PcDescSearch& search) { 1890 address base_address = search.code_begin(); 1891 if ((pc < base_address) || 1892 (pc - base_address) >= (ptrdiff_t) PcDesc::upper_offset_limit) { 1893 return NULL; // PC is wildly out of range 1894 } 1895 int pc_offset = (int) (pc - base_address); 1896 1897 // Check the PcDesc cache if it contains the desired PcDesc 1898 // (This as an almost 100% hit rate.) 1899 PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate); 1900 if (res != NULL) { 1901 assert(res == linear_search(search, pc_offset, approximate), "cache ok"); 1902 return res; 1903 } 1904 1905 // Fallback algorithm: quasi-linear search for the PcDesc 1906 // Find the last pc_offset less than the given offset. 1907 // The successor must be the required match, if there is a match at all. 1908 // (Use a fixed radix to avoid expensive affine pointer arithmetic.) 1909 PcDesc* lower = search.scopes_pcs_begin(); 1910 PcDesc* upper = search.scopes_pcs_end(); 1911 upper -= 1; // exclude final sentinel 1912 if (lower >= upper) return NULL; // native method; no PcDescs at all 1913 1914 #define assert_LU_OK \ 1915 /* invariant on lower..upper during the following search: */ \ 1916 assert(lower->pc_offset() < pc_offset, "sanity"); \ 1917 assert(upper->pc_offset() >= pc_offset, "sanity") 1918 assert_LU_OK; 1919 1920 // Use the last successful return as a split point. 1921 PcDesc* mid = _pc_desc_cache.last_pc_desc(); 1922 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches); 1923 if (mid->pc_offset() < pc_offset) { 1924 lower = mid; 1925 } else { 1926 upper = mid; 1927 } 1928 1929 // Take giant steps at first (4096, then 256, then 16, then 1) 1930 const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ debug_only(-1); 1931 const int RADIX = (1 << LOG2_RADIX); 1932 for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) { 1933 while ((mid = lower + step) < upper) { 1934 assert_LU_OK; 1935 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches); 1936 if (mid->pc_offset() < pc_offset) { 1937 lower = mid; 1938 } else { 1939 upper = mid; 1940 break; 1941 } 1942 } 1943 assert_LU_OK; 1944 } 1945 1946 // Sneak up on the value with a linear search of length ~16. 1947 while (true) { 1948 assert_LU_OK; 1949 mid = lower + 1; 1950 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches); 1951 if (mid->pc_offset() < pc_offset) { 1952 lower = mid; 1953 } else { 1954 upper = mid; 1955 break; 1956 } 1957 } 1958 #undef assert_LU_OK 1959 1960 if (match_desc(upper, pc_offset, approximate)) { 1961 assert(upper == linear_search(search, pc_offset, approximate), "search ok"); 1962 _pc_desc_cache.add_pc_desc(upper); 1963 return upper; 1964 } else { 1965 assert(NULL == linear_search(search, pc_offset, approximate), "search ok"); 1966 return NULL; 1967 } 1968 } 1969 1970 1971 void nmethod::check_all_dependencies(DepChange& changes) { 1972 // Checked dependencies are allocated into this ResourceMark 1973 ResourceMark rm; 1974 1975 // Turn off dependency tracing while actually testing dependencies. 1976 NOT_PRODUCT( FlagSetting fs(TraceDependencies, false) ); 1977 1978 typedef ResourceHashtable<DependencySignature, int, &DependencySignature::hash, 1979 &DependencySignature::equals, 11027> DepTable; 1980 1981 DepTable* table = new DepTable(); 1982 1983 // Iterate over live nmethods and check dependencies of all nmethods that are not 1984 // marked for deoptimization. A particular dependency is only checked once. 1985 NMethodIterator iter(NMethodIterator::only_alive_and_not_unloading); 1986 while(iter.next()) { 1987 nmethod* nm = iter.method(); 1988 // Only notify for live nmethods 1989 if (!nm->is_marked_for_deoptimization()) { 1990 for (Dependencies::DepStream deps(nm); deps.next(); ) { 1991 // Construct abstraction of a dependency. 1992 DependencySignature* current_sig = new DependencySignature(deps); 1993 1994 // Determine if dependency is already checked. table->put(...) returns 1995 // 'true' if the dependency is added (i.e., was not in the hashtable). 1996 if (table->put(*current_sig, 1)) { 1997 if (deps.check_dependency() != NULL) { 1998 // Dependency checking failed. Print out information about the failed 1999 // dependency and finally fail with an assert. We can fail here, since 2000 // dependency checking is never done in a product build. 2001 tty->print_cr("Failed dependency:"); 2002 changes.print(); 2003 nm->print(); 2004 nm->print_dependencies(); 2005 assert(false, "Should have been marked for deoptimization"); 2006 } 2007 } 2008 } 2009 } 2010 } 2011 } 2012 2013 bool nmethod::check_dependency_on(DepChange& changes) { 2014 // What has happened: 2015 // 1) a new class dependee has been added 2016 // 2) dependee and all its super classes have been marked 2017 bool found_check = false; // set true if we are upset 2018 for (Dependencies::DepStream deps(this); deps.next(); ) { 2019 // Evaluate only relevant dependencies. 2020 if (deps.spot_check_dependency_at(changes) != NULL) { 2021 found_check = true; 2022 NOT_DEBUG(break); 2023 } 2024 } 2025 return found_check; 2026 } 2027 2028 // Called from mark_for_deoptimization, when dependee is invalidated. 2029 bool nmethod::is_dependent_on_method(Method* dependee) { 2030 for (Dependencies::DepStream deps(this); deps.next(); ) { 2031 if (deps.type() != Dependencies::evol_method) 2032 continue; 2033 Method* method = deps.method_argument(0); 2034 if (method == dependee) return true; 2035 } 2036 return false; 2037 } 2038 2039 2040 bool nmethod::is_patchable_at(address instr_addr) { 2041 assert(insts_contains(instr_addr), "wrong nmethod used"); 2042 if (is_zombie()) { 2043 // a zombie may never be patched 2044 return false; 2045 } 2046 return true; 2047 } 2048 2049 2050 address nmethod::continuation_for_implicit_exception(address pc) { 2051 // Exception happened outside inline-cache check code => we are inside 2052 // an active nmethod => use cpc to determine a return address 2053 int exception_offset = pc - code_begin(); 2054 int cont_offset = ImplicitExceptionTable(this).at( exception_offset ); 2055 #ifdef ASSERT 2056 if (cont_offset == 0) { 2057 Thread* thread = Thread::current(); 2058 ResetNoHandleMark rnm; // Might be called from LEAF/QUICK ENTRY 2059 HandleMark hm(thread); 2060 ResourceMark rm(thread); 2061 CodeBlob* cb = CodeCache::find_blob(pc); 2062 assert(cb != NULL && cb == this, ""); 2063 ttyLocker ttyl; 2064 tty->print_cr("implicit exception happened at " INTPTR_FORMAT, p2i(pc)); 2065 print(); 2066 method()->print_codes(); 2067 print_code(); 2068 print_pcs(); 2069 } 2070 #endif 2071 if (cont_offset == 0) { 2072 // Let the normal error handling report the exception 2073 return NULL; 2074 } 2075 return code_begin() + cont_offset; 2076 } 2077 2078 2079 2080 void nmethod_init() { 2081 // make sure you didn't forget to adjust the filler fields 2082 assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word"); 2083 } 2084 2085 2086 //------------------------------------------------------------------------------------------- 2087 2088 2089 // QQQ might we make this work from a frame?? 2090 nmethodLocker::nmethodLocker(address pc) { 2091 CodeBlob* cb = CodeCache::find_blob(pc); 2092 guarantee(cb != NULL && cb->is_compiled(), "bad pc for a nmethod found"); 2093 _nm = cb->as_compiled_method(); 2094 lock_nmethod(_nm); 2095 } 2096 2097 // Only JvmtiDeferredEvent::compiled_method_unload_event() 2098 // should pass zombie_ok == true. 2099 void nmethodLocker::lock_nmethod(CompiledMethod* cm, bool zombie_ok) { 2100 if (cm == NULL) return; 2101 if (cm->is_aot()) return; // FIXME: Revisit once _lock_count is added to aot_method 2102 nmethod* nm = cm->as_nmethod(); 2103 Atomic::inc(&nm->_lock_count); 2104 assert(zombie_ok || !nm->is_zombie(), "cannot lock a zombie method: %p", nm); 2105 } 2106 2107 void nmethodLocker::unlock_nmethod(CompiledMethod* cm) { 2108 if (cm == NULL) return; 2109 if (cm->is_aot()) return; // FIXME: Revisit once _lock_count is added to aot_method 2110 nmethod* nm = cm->as_nmethod(); 2111 Atomic::dec(&nm->_lock_count); 2112 assert(nm->_lock_count >= 0, "unmatched nmethod lock/unlock"); 2113 } 2114 2115 2116 // ----------------------------------------------------------------------------- 2117 // Verification 2118 2119 class VerifyOopsClosure: public OopClosure { 2120 nmethod* _nm; 2121 bool _ok; 2122 public: 2123 VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { } 2124 bool ok() { return _ok; } 2125 virtual void do_oop(oop* p) { 2126 if (oopDesc::is_oop_or_null(*p)) return; 2127 if (_ok) { 2128 _nm->print_nmethod(true); 2129 _ok = false; 2130 } 2131 tty->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)", 2132 p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm)); 2133 } 2134 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); } 2135 }; 2136 2137 void nmethod::verify() { 2138 2139 // Hmm. OSR methods can be deopted but not marked as zombie or not_entrant 2140 // seems odd. 2141 2142 if (is_zombie() || is_not_entrant() || is_unloaded()) 2143 return; 2144 2145 // Make sure all the entry points are correctly aligned for patching. 2146 NativeJump::check_verified_entry_alignment(entry_point(), verified_entry_point()); 2147 2148 // assert(oopDesc::is_oop(method()), "must be valid"); 2149 2150 ResourceMark rm; 2151 2152 if (!CodeCache::contains(this)) { 2153 fatal("nmethod at " INTPTR_FORMAT " not in zone", p2i(this)); 2154 } 2155 2156 if(is_native_method() ) 2157 return; 2158 2159 nmethod* nm = CodeCache::find_nmethod(verified_entry_point()); 2160 if (nm != this) { 2161 fatal("findNMethod did not find this nmethod (" INTPTR_FORMAT ")", p2i(this)); 2162 } 2163 2164 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) { 2165 if (! p->verify(this)) { 2166 tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", p2i(this)); 2167 } 2168 } 2169 2170 VerifyOopsClosure voc(this); 2171 oops_do(&voc); 2172 assert(voc.ok(), "embedded oops must be OK"); 2173 Universe::heap()->verify_nmethod(this); 2174 2175 verify_scopes(); 2176 } 2177 2178 2179 void nmethod::verify_interrupt_point(address call_site) { 2180 // Verify IC only when nmethod installation is finished. 2181 if (!is_not_installed()) { 2182 if (CompiledICLocker::is_safe(this)) { 2183 CompiledIC_at(this, call_site); 2184 CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops()); 2185 } else { 2186 CompiledICLocker ml_verify(this); 2187 CompiledIC_at(this, call_site); 2188 } 2189 } 2190 2191 PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address()); 2192 assert(pd != NULL, "PcDesc must exist"); 2193 for (ScopeDesc* sd = new ScopeDesc(this, pd->scope_decode_offset(), 2194 pd->obj_decode_offset(), pd->should_reexecute(), pd->rethrow_exception(), 2195 pd->return_oop()); 2196 !sd->is_top(); sd = sd->sender()) { 2197 sd->verify(); 2198 } 2199 } 2200 2201 void nmethod::verify_scopes() { 2202 if( !method() ) return; // Runtime stubs have no scope 2203 if (method()->is_native()) return; // Ignore stub methods. 2204 // iterate through all interrupt point 2205 // and verify the debug information is valid. 2206 RelocIterator iter((nmethod*)this); 2207 while (iter.next()) { 2208 address stub = NULL; 2209 switch (iter.type()) { 2210 case relocInfo::virtual_call_type: 2211 verify_interrupt_point(iter.addr()); 2212 break; 2213 case relocInfo::opt_virtual_call_type: 2214 stub = iter.opt_virtual_call_reloc()->static_stub(false); 2215 verify_interrupt_point(iter.addr()); 2216 break; 2217 case relocInfo::static_call_type: 2218 stub = iter.static_call_reloc()->static_stub(false); 2219 //verify_interrupt_point(iter.addr()); 2220 break; 2221 case relocInfo::runtime_call_type: 2222 case relocInfo::runtime_call_w_cp_type: { 2223 address destination = iter.reloc()->value(); 2224 // Right now there is no way to find out which entries support 2225 // an interrupt point. It would be nice if we had this 2226 // information in a table. 2227 break; 2228 } 2229 default: 2230 break; 2231 } 2232 assert(stub == NULL || stub_contains(stub), "static call stub outside stub section"); 2233 } 2234 } 2235 2236 2237 // ----------------------------------------------------------------------------- 2238 // Printing operations 2239 2240 void nmethod::print() const { 2241 ResourceMark rm; 2242 ttyLocker ttyl; // keep the following output all in one block 2243 2244 tty->print("Compiled method "); 2245 2246 if (is_compiled_by_c1()) { 2247 tty->print("(c1) "); 2248 } else if (is_compiled_by_c2()) { 2249 tty->print("(c2) "); 2250 } else if (is_compiled_by_jvmci()) { 2251 tty->print("(JVMCI) "); 2252 } else { 2253 tty->print("(nm) "); 2254 } 2255 2256 print_on(tty, NULL); 2257 2258 if (WizardMode) { 2259 tty->print("((nmethod*) " INTPTR_FORMAT ") ", p2i(this)); 2260 tty->print(" for method " INTPTR_FORMAT , p2i(method())); 2261 tty->print(" { "); 2262 tty->print_cr("%s ", state()); 2263 tty->print_cr("}:"); 2264 } 2265 if (size () > 0) tty->print_cr(" total in heap [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2266 p2i(this), 2267 p2i(this) + size(), 2268 size()); 2269 if (relocation_size () > 0) tty->print_cr(" relocation [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2270 p2i(relocation_begin()), 2271 p2i(relocation_end()), 2272 relocation_size()); 2273 if (consts_size () > 0) tty->print_cr(" constants [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2274 p2i(consts_begin()), 2275 p2i(consts_end()), 2276 consts_size()); 2277 if (insts_size () > 0) tty->print_cr(" main code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2278 p2i(insts_begin()), 2279 p2i(insts_end()), 2280 insts_size()); 2281 if (stub_size () > 0) tty->print_cr(" stub code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2282 p2i(stub_begin()), 2283 p2i(stub_end()), 2284 stub_size()); 2285 if (oops_size () > 0) tty->print_cr(" oops [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2286 p2i(oops_begin()), 2287 p2i(oops_end()), 2288 oops_size()); 2289 if (metadata_size () > 0) tty->print_cr(" metadata [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2290 p2i(metadata_begin()), 2291 p2i(metadata_end()), 2292 metadata_size()); 2293 if (scopes_data_size () > 0) tty->print_cr(" scopes data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2294 p2i(scopes_data_begin()), 2295 p2i(scopes_data_end()), 2296 scopes_data_size()); 2297 if (scopes_pcs_size () > 0) tty->print_cr(" scopes pcs [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2298 p2i(scopes_pcs_begin()), 2299 p2i(scopes_pcs_end()), 2300 scopes_pcs_size()); 2301 if (dependencies_size () > 0) tty->print_cr(" dependencies [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2302 p2i(dependencies_begin()), 2303 p2i(dependencies_end()), 2304 dependencies_size()); 2305 if (handler_table_size() > 0) tty->print_cr(" handler table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2306 p2i(handler_table_begin()), 2307 p2i(handler_table_end()), 2308 handler_table_size()); 2309 if (nul_chk_table_size() > 0) tty->print_cr(" nul chk table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2310 p2i(nul_chk_table_begin()), 2311 p2i(nul_chk_table_end()), 2312 nul_chk_table_size()); 2313 #if INCLUDE_JVMCI 2314 if (speculations_size () > 0) tty->print_cr(" speculations [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2315 p2i(speculations_begin()), 2316 p2i(speculations_end()), 2317 speculations_size()); 2318 if (jvmci_data_size () > 0) tty->print_cr(" JVMCI data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2319 p2i(jvmci_data_begin()), 2320 p2i(jvmci_data_end()), 2321 jvmci_data_size()); 2322 #endif 2323 } 2324 2325 #ifndef PRODUCT 2326 2327 void nmethod::print_scopes() { 2328 // Find the first pc desc for all scopes in the code and print it. 2329 ResourceMark rm; 2330 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) { 2331 if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null) 2332 continue; 2333 2334 ScopeDesc* sd = scope_desc_at(p->real_pc(this)); 2335 while (sd != NULL) { 2336 sd->print_on(tty, p); 2337 sd = sd->sender(); 2338 } 2339 } 2340 } 2341 2342 void nmethod::print_dependencies() { 2343 ResourceMark rm; 2344 ttyLocker ttyl; // keep the following output all in one block 2345 tty->print_cr("Dependencies:"); 2346 for (Dependencies::DepStream deps(this); deps.next(); ) { 2347 deps.print_dependency(); 2348 Klass* ctxk = deps.context_type(); 2349 if (ctxk != NULL) { 2350 if (ctxk->is_instance_klass() && InstanceKlass::cast(ctxk)->is_dependent_nmethod(this)) { 2351 tty->print_cr(" [nmethod<=klass]%s", ctxk->external_name()); 2352 } 2353 } 2354 deps.log_dependency(); // put it into the xml log also 2355 } 2356 } 2357 2358 2359 void nmethod::print_relocations() { 2360 ResourceMark m; // in case methods get printed via the debugger 2361 tty->print_cr("relocations:"); 2362 RelocIterator iter(this); 2363 iter.print(); 2364 } 2365 2366 2367 void nmethod::print_pcs() { 2368 ResourceMark m; // in case methods get printed via debugger 2369 tty->print_cr("pc-bytecode offsets:"); 2370 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) { 2371 p->print(this); 2372 } 2373 } 2374 2375 void nmethod::print_recorded_oops() { 2376 tty->print_cr("Recorded oops:"); 2377 for (int i = 0; i < oops_count(); i++) { 2378 oop o = oop_at(i); 2379 tty->print("#%3d: " INTPTR_FORMAT " ", i, p2i(o)); 2380 if (o == Universe::non_oop_word()) { 2381 tty->print("non-oop word"); 2382 } else { 2383 if (o != NULL) { 2384 o->print_value(); 2385 } else { 2386 tty->print_cr("NULL"); 2387 } 2388 } 2389 tty->cr(); 2390 } 2391 } 2392 2393 void nmethod::print_recorded_metadata() { 2394 tty->print_cr("Recorded metadata:"); 2395 for (int i = 0; i < metadata_count(); i++) { 2396 Metadata* m = metadata_at(i); 2397 tty->print("#%3d: " INTPTR_FORMAT " ", i, p2i(m)); 2398 if (m == (Metadata*)Universe::non_oop_word()) { 2399 tty->print("non-metadata word"); 2400 } else { 2401 Metadata::print_value_on_maybe_null(tty, m); 2402 } 2403 tty->cr(); 2404 } 2405 } 2406 2407 #endif // PRODUCT 2408 2409 const char* nmethod::reloc_string_for(u_char* begin, u_char* end) { 2410 RelocIterator iter(this, begin, end); 2411 bool have_one = false; 2412 while (iter.next()) { 2413 have_one = true; 2414 switch (iter.type()) { 2415 case relocInfo::none: return "no_reloc"; 2416 case relocInfo::oop_type: { 2417 stringStream st; 2418 oop_Relocation* r = iter.oop_reloc(); 2419 oop obj = r->oop_value(); 2420 st.print("oop("); 2421 if (obj == NULL) st.print("NULL"); 2422 else obj->print_value_on(&st); 2423 st.print(")"); 2424 return st.as_string(); 2425 } 2426 case relocInfo::metadata_type: { 2427 stringStream st; 2428 metadata_Relocation* r = iter.metadata_reloc(); 2429 Metadata* obj = r->metadata_value(); 2430 st.print("metadata("); 2431 if (obj == NULL) st.print("NULL"); 2432 else obj->print_value_on(&st); 2433 st.print(")"); 2434 return st.as_string(); 2435 } 2436 case relocInfo::runtime_call_type: 2437 case relocInfo::runtime_call_w_cp_type: { 2438 stringStream st; 2439 st.print("runtime_call"); 2440 CallRelocation* r = (CallRelocation*)iter.reloc(); 2441 address dest = r->destination(); 2442 CodeBlob* cb = CodeCache::find_blob(dest); 2443 if (cb != NULL) { 2444 st.print(" %s", cb->name()); 2445 } else { 2446 ResourceMark rm; 2447 const int buflen = 1024; 2448 char* buf = NEW_RESOURCE_ARRAY(char, buflen); 2449 int offset; 2450 if (os::dll_address_to_function_name(dest, buf, buflen, &offset)) { 2451 st.print(" %s", buf); 2452 if (offset != 0) { 2453 st.print("+%d", offset); 2454 } 2455 } 2456 } 2457 return st.as_string(); 2458 } 2459 case relocInfo::virtual_call_type: { 2460 stringStream st; 2461 st.print_raw("virtual_call"); 2462 virtual_call_Relocation* r = iter.virtual_call_reloc(); 2463 Method* m = r->method_value(); 2464 if (m != NULL) { 2465 assert(m->is_method(), ""); 2466 m->print_short_name(&st); 2467 } 2468 return st.as_string(); 2469 } 2470 case relocInfo::opt_virtual_call_type: { 2471 stringStream st; 2472 st.print_raw("optimized virtual_call"); 2473 opt_virtual_call_Relocation* r = iter.opt_virtual_call_reloc(); 2474 Method* m = r->method_value(); 2475 if (m != NULL) { 2476 assert(m->is_method(), ""); 2477 m->print_short_name(&st); 2478 } 2479 return st.as_string(); 2480 } 2481 case relocInfo::static_call_type: { 2482 stringStream st; 2483 st.print_raw("static_call"); 2484 static_call_Relocation* r = iter.static_call_reloc(); 2485 Method* m = r->method_value(); 2486 if (m != NULL) { 2487 assert(m->is_method(), ""); 2488 m->print_short_name(&st); 2489 } 2490 return st.as_string(); 2491 } 2492 case relocInfo::static_stub_type: return "static_stub"; 2493 case relocInfo::external_word_type: return "external_word"; 2494 case relocInfo::internal_word_type: return "internal_word"; 2495 case relocInfo::section_word_type: return "section_word"; 2496 case relocInfo::poll_type: return "poll"; 2497 case relocInfo::poll_return_type: return "poll_return"; 2498 case relocInfo::trampoline_stub_type: return "trampoline_stub"; 2499 case relocInfo::type_mask: return "type_bit_mask"; 2500 2501 default: 2502 break; 2503 } 2504 } 2505 return have_one ? "other" : NULL; 2506 } 2507 2508 // Return a the last scope in (begin..end] 2509 ScopeDesc* nmethod::scope_desc_in(address begin, address end) { 2510 PcDesc* p = pc_desc_near(begin+1); 2511 if (p != NULL && p->real_pc(this) <= end) { 2512 return new ScopeDesc(this, p->scope_decode_offset(), 2513 p->obj_decode_offset(), p->should_reexecute(), p->rethrow_exception(), 2514 p->return_oop()); 2515 } 2516 return NULL; 2517 } 2518 2519 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin) const { 2520 if (block_begin == entry_point()) stream->print_cr("[Entry Point]"); 2521 if (block_begin == verified_entry_point()) stream->print_cr("[Verified Entry Point]"); 2522 if (JVMCI_ONLY(_exception_offset >= 0 &&) block_begin == exception_begin()) stream->print_cr("[Exception Handler]"); 2523 if (block_begin == stub_begin()) stream->print_cr("[Stub Code]"); 2524 if (JVMCI_ONLY(_deopt_handler_begin != NULL &&) block_begin == deopt_handler_begin()) stream->print_cr("[Deopt Handler Code]"); 2525 2526 if (has_method_handle_invokes()) 2527 if (block_begin == deopt_mh_handler_begin()) stream->print_cr("[Deopt MH Handler Code]"); 2528 2529 if (block_begin == consts_begin()) stream->print_cr("[Constants]"); 2530 2531 if (block_begin == entry_point()) { 2532 methodHandle m = method(); 2533 if (m.not_null()) { 2534 stream->print(" # "); 2535 m->print_value_on(stream); 2536 stream->cr(); 2537 } 2538 if (m.not_null() && !is_osr_method()) { 2539 ResourceMark rm; 2540 int sizeargs = m->size_of_parameters(); 2541 BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs); 2542 VMRegPair* regs = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs); 2543 { 2544 int sig_index = 0; 2545 if (!m->is_static()) 2546 sig_bt[sig_index++] = T_OBJECT; // 'this' 2547 for (SignatureStream ss(m->signature()); !ss.at_return_type(); ss.next()) { 2548 BasicType t = ss.type(); 2549 sig_bt[sig_index++] = t; 2550 if (type2size[t] == 2) { 2551 sig_bt[sig_index++] = T_VOID; 2552 } else { 2553 assert(type2size[t] == 1, "size is 1 or 2"); 2554 } 2555 } 2556 assert(sig_index == sizeargs, ""); 2557 } 2558 const char* spname = "sp"; // make arch-specific? 2559 intptr_t out_preserve = SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs, false); 2560 int stack_slot_offset = this->frame_size() * wordSize; 2561 int tab1 = 14, tab2 = 24; 2562 int sig_index = 0; 2563 int arg_index = (m->is_static() ? 0 : -1); 2564 bool did_old_sp = false; 2565 for (SignatureStream ss(m->signature()); !ss.at_return_type(); ) { 2566 bool at_this = (arg_index == -1); 2567 bool at_old_sp = false; 2568 BasicType t = (at_this ? T_OBJECT : ss.type()); 2569 assert(t == sig_bt[sig_index], "sigs in sync"); 2570 if (at_this) 2571 stream->print(" # this: "); 2572 else 2573 stream->print(" # parm%d: ", arg_index); 2574 stream->move_to(tab1); 2575 VMReg fst = regs[sig_index].first(); 2576 VMReg snd = regs[sig_index].second(); 2577 if (fst->is_reg()) { 2578 stream->print("%s", fst->name()); 2579 if (snd->is_valid()) { 2580 stream->print(":%s", snd->name()); 2581 } 2582 } else if (fst->is_stack()) { 2583 int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset; 2584 if (offset == stack_slot_offset) at_old_sp = true; 2585 stream->print("[%s+0x%x]", spname, offset); 2586 } else { 2587 stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd); 2588 } 2589 stream->print(" "); 2590 stream->move_to(tab2); 2591 stream->print("= "); 2592 if (at_this) { 2593 m->method_holder()->print_value_on(stream); 2594 } else { 2595 bool did_name = false; 2596 if (!at_this && ss.is_object()) { 2597 Symbol* name = ss.as_symbol_or_null(); 2598 if (name != NULL) { 2599 name->print_value_on(stream); 2600 did_name = true; 2601 } 2602 } 2603 if (!did_name) 2604 stream->print("%s", type2name(t)); 2605 } 2606 if (at_old_sp) { 2607 stream->print(" (%s of caller)", spname); 2608 did_old_sp = true; 2609 } 2610 stream->cr(); 2611 sig_index += type2size[t]; 2612 arg_index += 1; 2613 if (!at_this) ss.next(); 2614 } 2615 if (!did_old_sp) { 2616 stream->print(" # "); 2617 stream->move_to(tab1); 2618 stream->print("[%s+0x%x]", spname, stack_slot_offset); 2619 stream->print(" (%s of caller)", spname); 2620 stream->cr(); 2621 } 2622 } 2623 } 2624 } 2625 2626 void nmethod::print_code_comment_on(outputStream* st, int column, u_char* begin, u_char* end) { 2627 // First, find an oopmap in (begin, end]. 2628 // We use the odd half-closed interval so that oop maps and scope descs 2629 // which are tied to the byte after a call are printed with the call itself. 2630 address base = code_begin(); 2631 ImmutableOopMapSet* oms = oop_maps(); 2632 if (oms != NULL) { 2633 for (int i = 0, imax = oms->count(); i < imax; i++) { 2634 const ImmutableOopMapPair* pair = oms->pair_at(i); 2635 const ImmutableOopMap* om = pair->get_from(oms); 2636 address pc = base + pair->pc_offset(); 2637 if (pc > begin) { 2638 if (pc <= end) { 2639 st->move_to(column); 2640 st->print("; "); 2641 om->print_on(st); 2642 } 2643 break; 2644 } 2645 } 2646 } 2647 2648 // Print any debug info present at this pc. 2649 ScopeDesc* sd = scope_desc_in(begin, end); 2650 if (sd != NULL) { 2651 st->move_to(column); 2652 if (sd->bci() == SynchronizationEntryBCI) { 2653 st->print(";*synchronization entry"); 2654 } else if (sd->bci() == AfterBci) { 2655 st->print(";* method exit (unlocked if synchronized)"); 2656 } else if (sd->bci() == UnwindBci) { 2657 st->print(";* unwind (locked if synchronized)"); 2658 } else if (sd->bci() == AfterExceptionBci) { 2659 st->print(";* unwind (unlocked if synchronized)"); 2660 } else if (sd->bci() == UnknownBci) { 2661 st->print(";* unknown"); 2662 } else if (sd->bci() == InvalidFrameStateBci) { 2663 st->print(";* invalid frame state"); 2664 } else { 2665 if (sd->method() == NULL) { 2666 st->print("method is NULL"); 2667 } else if (sd->method()->is_native()) { 2668 st->print("method is native"); 2669 } else { 2670 Bytecodes::Code bc = sd->method()->java_code_at(sd->bci()); 2671 st->print(";*%s", Bytecodes::name(bc)); 2672 switch (bc) { 2673 case Bytecodes::_invokevirtual: 2674 case Bytecodes::_invokespecial: 2675 case Bytecodes::_invokestatic: 2676 case Bytecodes::_invokeinterface: 2677 { 2678 Bytecode_invoke invoke(sd->method(), sd->bci()); 2679 st->print(" "); 2680 if (invoke.name() != NULL) 2681 invoke.name()->print_symbol_on(st); 2682 else 2683 st->print("<UNKNOWN>"); 2684 break; 2685 } 2686 case Bytecodes::_getfield: 2687 case Bytecodes::_putfield: 2688 case Bytecodes::_getstatic: 2689 case Bytecodes::_putstatic: 2690 { 2691 Bytecode_field field(sd->method(), sd->bci()); 2692 st->print(" "); 2693 if (field.name() != NULL) 2694 field.name()->print_symbol_on(st); 2695 else 2696 st->print("<UNKNOWN>"); 2697 } 2698 default: 2699 break; 2700 } 2701 } 2702 st->print(" {reexecute=%d rethrow=%d return_oop=%d}", sd->should_reexecute(), sd->rethrow_exception(), sd->return_oop()); 2703 } 2704 2705 // Print all scopes 2706 for (;sd != NULL; sd = sd->sender()) { 2707 st->move_to(column); 2708 st->print("; -"); 2709 if (sd->method() == NULL) { 2710 st->print("method is NULL"); 2711 } else { 2712 sd->method()->print_short_name(st); 2713 } 2714 int lineno = sd->method()->line_number_from_bci(sd->bci()); 2715 if (lineno != -1) { 2716 st->print("@%d (line %d)", sd->bci(), lineno); 2717 } else { 2718 st->print("@%d", sd->bci()); 2719 } 2720 st->cr(); 2721 } 2722 } 2723 2724 // Print relocation information 2725 const char* str = reloc_string_for(begin, end); 2726 if (str != NULL) { 2727 if (sd != NULL) st->cr(); 2728 st->move_to(column); 2729 st->print("; {%s}", str); 2730 } 2731 int cont_offset = ImplicitExceptionTable(this).at(begin - code_begin()); 2732 if (cont_offset != 0) { 2733 st->move_to(column); 2734 st->print("; implicit exception: dispatches to " INTPTR_FORMAT, p2i(code_begin() + cont_offset)); 2735 } 2736 2737 } 2738 2739 class DirectNativeCallWrapper: public NativeCallWrapper { 2740 private: 2741 NativeCall* _call; 2742 2743 public: 2744 DirectNativeCallWrapper(NativeCall* call) : _call(call) {} 2745 2746 virtual address destination() const { return _call->destination(); } 2747 virtual address instruction_address() const { return _call->instruction_address(); } 2748 virtual address next_instruction_address() const { return _call->next_instruction_address(); } 2749 virtual address return_address() const { return _call->return_address(); } 2750 2751 virtual address get_resolve_call_stub(bool is_optimized) const { 2752 if (is_optimized) { 2753 return SharedRuntime::get_resolve_opt_virtual_call_stub(); 2754 } 2755 return SharedRuntime::get_resolve_virtual_call_stub(); 2756 } 2757 2758 virtual void set_destination_mt_safe(address dest) { 2759 #if INCLUDE_AOT 2760 if (UseAOT) { 2761 CodeBlob* callee = CodeCache::find_blob(dest); 2762 CompiledMethod* cm = callee->as_compiled_method_or_null(); 2763 if (cm != NULL && cm->is_far_code()) { 2764 // Temporary fix, see JDK-8143106 2765 CompiledDirectStaticCall* csc = CompiledDirectStaticCall::at(instruction_address()); 2766 csc->set_to_far(methodHandle(cm->method()), dest); 2767 return; 2768 } 2769 } 2770 #endif 2771 _call->set_destination_mt_safe(dest); 2772 } 2773 2774 virtual void set_to_interpreted(const methodHandle& method, CompiledICInfo& info) { 2775 CompiledDirectStaticCall* csc = CompiledDirectStaticCall::at(instruction_address()); 2776 #if INCLUDE_AOT 2777 if (info.to_aot()) { 2778 csc->set_to_far(method, info.entry()); 2779 } else 2780 #endif 2781 { 2782 csc->set_to_interpreted(method, info.entry()); 2783 } 2784 } 2785 2786 virtual void verify() const { 2787 // make sure code pattern is actually a call imm32 instruction 2788 _call->verify(); 2789 _call->verify_alignment(); 2790 } 2791 2792 virtual void verify_resolve_call(address dest) const { 2793 CodeBlob* db = CodeCache::find_blob_unsafe(dest); 2794 assert(db != NULL && !db->is_adapter_blob(), "must use stub!"); 2795 } 2796 2797 virtual bool is_call_to_interpreted(address dest) const { 2798 CodeBlob* cb = CodeCache::find_blob(_call->instruction_address()); 2799 return cb->contains(dest); 2800 } 2801 2802 virtual bool is_safe_for_patching() const { return false; } 2803 2804 virtual NativeInstruction* get_load_instruction(virtual_call_Relocation* r) const { 2805 return nativeMovConstReg_at(r->cached_value()); 2806 } 2807 2808 virtual void *get_data(NativeInstruction* instruction) const { 2809 return (void*)((NativeMovConstReg*) instruction)->data(); 2810 } 2811 2812 virtual void set_data(NativeInstruction* instruction, intptr_t data) { 2813 ((NativeMovConstReg*) instruction)->set_data(data); 2814 } 2815 }; 2816 2817 NativeCallWrapper* nmethod::call_wrapper_at(address call) const { 2818 return new DirectNativeCallWrapper((NativeCall*) call); 2819 } 2820 2821 NativeCallWrapper* nmethod::call_wrapper_before(address return_pc) const { 2822 return new DirectNativeCallWrapper(nativeCall_before(return_pc)); 2823 } 2824 2825 address nmethod::call_instruction_address(address pc) const { 2826 if (NativeCall::is_call_before(pc)) { 2827 NativeCall *ncall = nativeCall_before(pc); 2828 return ncall->instruction_address(); 2829 } 2830 return NULL; 2831 } 2832 2833 CompiledStaticCall* nmethod::compiledStaticCall_at(Relocation* call_site) const { 2834 return CompiledDirectStaticCall::at(call_site); 2835 } 2836 2837 CompiledStaticCall* nmethod::compiledStaticCall_at(address call_site) const { 2838 return CompiledDirectStaticCall::at(call_site); 2839 } 2840 2841 CompiledStaticCall* nmethod::compiledStaticCall_before(address return_addr) const { 2842 return CompiledDirectStaticCall::before(return_addr); 2843 } 2844 2845 #ifndef PRODUCT 2846 2847 void nmethod::print_value_on(outputStream* st) const { 2848 st->print("nmethod"); 2849 print_on(st, NULL); 2850 } 2851 2852 void nmethod::print_calls(outputStream* st) { 2853 RelocIterator iter(this); 2854 while (iter.next()) { 2855 switch (iter.type()) { 2856 case relocInfo::virtual_call_type: 2857 case relocInfo::opt_virtual_call_type: { 2858 CompiledICLocker ml_verify(this); 2859 CompiledIC_at(&iter)->print(); 2860 break; 2861 } 2862 case relocInfo::static_call_type: 2863 st->print_cr("Static call at " INTPTR_FORMAT, p2i(iter.reloc()->addr())); 2864 CompiledDirectStaticCall::at(iter.reloc())->print(); 2865 break; 2866 default: 2867 break; 2868 } 2869 } 2870 } 2871 2872 void nmethod::print_handler_table() { 2873 ExceptionHandlerTable(this).print(); 2874 } 2875 2876 void nmethod::print_nul_chk_table() { 2877 ImplicitExceptionTable(this).print(code_begin()); 2878 } 2879 2880 void nmethod::print_statistics() { 2881 ttyLocker ttyl; 2882 if (xtty != NULL) xtty->head("statistics type='nmethod'"); 2883 native_nmethod_stats.print_native_nmethod_stats(); 2884 #ifdef COMPILER1 2885 c1_java_nmethod_stats.print_nmethod_stats("C1"); 2886 #endif 2887 #ifdef COMPILER2 2888 c2_java_nmethod_stats.print_nmethod_stats("C2"); 2889 #endif 2890 #if INCLUDE_JVMCI 2891 jvmci_java_nmethod_stats.print_nmethod_stats("JVMCI"); 2892 #endif 2893 unknown_java_nmethod_stats.print_nmethod_stats("Unknown"); 2894 DebugInformationRecorder::print_statistics(); 2895 #ifndef PRODUCT 2896 pc_nmethod_stats.print_pc_stats(); 2897 #endif 2898 Dependencies::print_statistics(); 2899 if (xtty != NULL) xtty->tail("statistics"); 2900 } 2901 2902 #endif // !PRODUCT 2903 2904 #if INCLUDE_JVMCI 2905 void nmethod::update_speculation(JavaThread* thread) { 2906 jlong speculation = thread->pending_failed_speculation(); 2907 if (speculation != 0) { 2908 guarantee(jvmci_nmethod_data() != NULL, "failed speculation in nmethod without failed speculation list"); 2909 jvmci_nmethod_data()->add_failed_speculation(this, speculation); 2910 thread->set_pending_failed_speculation(0); 2911 } 2912 } 2913 2914 const char* nmethod::jvmci_name() { 2915 if (jvmci_nmethod_data() != NULL) { 2916 return jvmci_nmethod_data()->name(); 2917 } 2918 return NULL; 2919 } 2920 #endif