Path: blob/master/src/hotspot/share/code/nmethod.cpp
40931 views
/*1* Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "jvm.h"26#include "asm/assembler.inline.hpp"27#include "code/codeCache.hpp"28#include "code/compiledIC.hpp"29#include "code/compiledMethod.inline.hpp"30#include "code/dependencies.hpp"31#include "code/nativeInst.hpp"32#include "code/nmethod.hpp"33#include "code/scopeDesc.hpp"34#include "compiler/abstractCompiler.hpp"35#include "compiler/compileBroker.hpp"36#include "compiler/compileLog.hpp"37#include "compiler/compilerDirectives.hpp"38#include "compiler/directivesParser.hpp"39#include "compiler/disassembler.hpp"40#include "compiler/oopMap.hpp"41#include "gc/shared/collectedHeap.hpp"42#include "interpreter/bytecode.hpp"43#include "logging/log.hpp"44#include "logging/logStream.hpp"45#include "memory/allocation.inline.hpp"46#include "memory/resourceArea.hpp"47#include "memory/universe.hpp"48#include "oops/access.inline.hpp"49#include "oops/klass.inline.hpp"50#include "oops/method.inline.hpp"51#include "oops/methodData.hpp"52#include "oops/oop.inline.hpp"53#include "prims/jvmtiImpl.hpp"54#include "prims/jvmtiThreadState.hpp"55#include "prims/methodHandles.hpp"56#include "runtime/atomic.hpp"57#include "runtime/deoptimization.hpp"58#include "runtime/flags/flagSetting.hpp"59#include "runtime/frame.inline.hpp"60#include "runtime/handles.inline.hpp"61#include "runtime/jniHandles.inline.hpp"62#include "runtime/orderAccess.hpp"63#include "runtime/os.hpp"64#include "runtime/safepointVerifiers.hpp"65#include "runtime/serviceThread.hpp"66#include "runtime/sharedRuntime.hpp"67#include "runtime/signature.hpp"68#include "runtime/sweeper.hpp"69#include "runtime/vmThread.hpp"70#include "utilities/align.hpp"71#include "utilities/copy.hpp"72#include "utilities/dtrace.hpp"73#include "utilities/events.hpp"74#include "utilities/globalDefinitions.hpp"75#include "utilities/resourceHash.hpp"76#include "utilities/xmlstream.hpp"77#if INCLUDE_JVMCI78#include "jvmci/jvmciRuntime.hpp"79#endif8081#ifdef DTRACE_ENABLED8283// Only bother with this argument setup if dtrace is available8485#define DTRACE_METHOD_UNLOAD_PROBE(method) \86{ \87Method* m = (method); \88if (m != NULL) { \89Symbol* klass_name = m->klass_name(); \90Symbol* name = m->name(); \91Symbol* signature = m->signature(); \92HOTSPOT_COMPILED_METHOD_UNLOAD( \93(char *) klass_name->bytes(), klass_name->utf8_length(), \94(char *) name->bytes(), name->utf8_length(), \95(char *) signature->bytes(), signature->utf8_length()); \96} \97}9899#else // ndef DTRACE_ENABLED100101#define DTRACE_METHOD_UNLOAD_PROBE(method)102103#endif104105//---------------------------------------------------------------------------------106// NMethod statistics107// They are printed under various flags, including:108// PrintC1Statistics, PrintOptoStatistics, LogVMOutput, and LogCompilation.109// (In the latter two cases, they like other stats are printed to the log only.)110111#ifndef PRODUCT112// These variables are put into one block to reduce relocations113// and make it simpler to print from the debugger.114struct java_nmethod_stats_struct {115int nmethod_count;116int total_size;117int relocation_size;118int consts_size;119int insts_size;120int stub_size;121int scopes_data_size;122int scopes_pcs_size;123int dependencies_size;124int handler_table_size;125int nul_chk_table_size;126#if INCLUDE_JVMCI127int speculations_size;128int jvmci_data_size;129#endif130int oops_size;131int metadata_size;132133void note_nmethod(nmethod* nm) {134nmethod_count += 1;135total_size += nm->size();136relocation_size += nm->relocation_size();137consts_size += nm->consts_size();138insts_size += nm->insts_size();139stub_size += nm->stub_size();140oops_size += nm->oops_size();141metadata_size += nm->metadata_size();142scopes_data_size += nm->scopes_data_size();143scopes_pcs_size += nm->scopes_pcs_size();144dependencies_size += nm->dependencies_size();145handler_table_size += nm->handler_table_size();146nul_chk_table_size += nm->nul_chk_table_size();147#if INCLUDE_JVMCI148speculations_size += nm->speculations_size();149jvmci_data_size += nm->jvmci_data_size();150#endif151}152void print_nmethod_stats(const char* name) {153if (nmethod_count == 0) return;154tty->print_cr("Statistics for %d bytecoded nmethods for %s:", nmethod_count, name);155if (total_size != 0) tty->print_cr(" total in heap = %d", total_size);156if (nmethod_count != 0) tty->print_cr(" header = " SIZE_FORMAT, nmethod_count * sizeof(nmethod));157if (relocation_size != 0) tty->print_cr(" relocation = %d", relocation_size);158if (consts_size != 0) tty->print_cr(" constants = %d", consts_size);159if (insts_size != 0) tty->print_cr(" main code = %d", insts_size);160if (stub_size != 0) tty->print_cr(" stub code = %d", stub_size);161if (oops_size != 0) tty->print_cr(" oops = %d", oops_size);162if (metadata_size != 0) tty->print_cr(" metadata = %d", metadata_size);163if (scopes_data_size != 0) tty->print_cr(" scopes data = %d", scopes_data_size);164if (scopes_pcs_size != 0) tty->print_cr(" scopes pcs = %d", scopes_pcs_size);165if (dependencies_size != 0) tty->print_cr(" dependencies = %d", dependencies_size);166if (handler_table_size != 0) tty->print_cr(" handler table = %d", handler_table_size);167if (nul_chk_table_size != 0) tty->print_cr(" nul chk table = %d", nul_chk_table_size);168#if INCLUDE_JVMCI169if (speculations_size != 0) tty->print_cr(" speculations = %d", speculations_size);170if (jvmci_data_size != 0) tty->print_cr(" JVMCI data = %d", jvmci_data_size);171#endif172}173};174175struct native_nmethod_stats_struct {176int native_nmethod_count;177int native_total_size;178int native_relocation_size;179int native_insts_size;180int native_oops_size;181int native_metadata_size;182void note_native_nmethod(nmethod* nm) {183native_nmethod_count += 1;184native_total_size += nm->size();185native_relocation_size += nm->relocation_size();186native_insts_size += nm->insts_size();187native_oops_size += nm->oops_size();188native_metadata_size += nm->metadata_size();189}190void print_native_nmethod_stats() {191if (native_nmethod_count == 0) return;192tty->print_cr("Statistics for %d native nmethods:", native_nmethod_count);193if (native_total_size != 0) tty->print_cr(" N. total size = %d", native_total_size);194if (native_relocation_size != 0) tty->print_cr(" N. relocation = %d", native_relocation_size);195if (native_insts_size != 0) tty->print_cr(" N. main code = %d", native_insts_size);196if (native_oops_size != 0) tty->print_cr(" N. oops = %d", native_oops_size);197if (native_metadata_size != 0) tty->print_cr(" N. metadata = %d", native_metadata_size);198}199};200201struct pc_nmethod_stats_struct {202int pc_desc_resets; // number of resets (= number of caches)203int pc_desc_queries; // queries to nmethod::find_pc_desc204int pc_desc_approx; // number of those which have approximate true205int pc_desc_repeats; // number of _pc_descs[0] hits206int pc_desc_hits; // number of LRU cache hits207int pc_desc_tests; // total number of PcDesc examinations208int pc_desc_searches; // total number of quasi-binary search steps209int pc_desc_adds; // number of LUR cache insertions210211void print_pc_stats() {212tty->print_cr("PcDesc Statistics: %d queries, %.2f comparisons per query",213pc_desc_queries,214(double)(pc_desc_tests + pc_desc_searches)215/ pc_desc_queries);216tty->print_cr(" caches=%d queries=%d/%d, hits=%d+%d, tests=%d+%d, adds=%d",217pc_desc_resets,218pc_desc_queries, pc_desc_approx,219pc_desc_repeats, pc_desc_hits,220pc_desc_tests, pc_desc_searches, pc_desc_adds);221}222};223224#ifdef COMPILER1225static java_nmethod_stats_struct c1_java_nmethod_stats;226#endif227#ifdef COMPILER2228static java_nmethod_stats_struct c2_java_nmethod_stats;229#endif230#if INCLUDE_JVMCI231static java_nmethod_stats_struct jvmci_java_nmethod_stats;232#endif233static java_nmethod_stats_struct unknown_java_nmethod_stats;234235static native_nmethod_stats_struct native_nmethod_stats;236static pc_nmethod_stats_struct pc_nmethod_stats;237238static void note_java_nmethod(nmethod* nm) {239#ifdef COMPILER1240if (nm->is_compiled_by_c1()) {241c1_java_nmethod_stats.note_nmethod(nm);242} else243#endif244#ifdef COMPILER2245if (nm->is_compiled_by_c2()) {246c2_java_nmethod_stats.note_nmethod(nm);247} else248#endif249#if INCLUDE_JVMCI250if (nm->is_compiled_by_jvmci()) {251jvmci_java_nmethod_stats.note_nmethod(nm);252} else253#endif254{255unknown_java_nmethod_stats.note_nmethod(nm);256}257}258#endif // !PRODUCT259260//---------------------------------------------------------------------------------261262263ExceptionCache::ExceptionCache(Handle exception, address pc, address handler) {264assert(pc != NULL, "Must be non null");265assert(exception.not_null(), "Must be non null");266assert(handler != NULL, "Must be non null");267268_count = 0;269_exception_type = exception->klass();270_next = NULL;271_purge_list_next = NULL;272273add_address_and_handler(pc,handler);274}275276277address ExceptionCache::match(Handle exception, address pc) {278assert(pc != NULL,"Must be non null");279assert(exception.not_null(),"Must be non null");280if (exception->klass() == exception_type()) {281return (test_address(pc));282}283284return NULL;285}286287288bool ExceptionCache::match_exception_with_space(Handle exception) {289assert(exception.not_null(),"Must be non null");290if (exception->klass() == exception_type() && count() < cache_size) {291return true;292}293return false;294}295296297address ExceptionCache::test_address(address addr) {298int limit = count();299for (int i = 0; i < limit; i++) {300if (pc_at(i) == addr) {301return handler_at(i);302}303}304return NULL;305}306307308bool ExceptionCache::add_address_and_handler(address addr, address handler) {309if (test_address(addr) == handler) return true;310311int index = count();312if (index < cache_size) {313set_pc_at(index, addr);314set_handler_at(index, handler);315increment_count();316return true;317}318return false;319}320321ExceptionCache* ExceptionCache::next() {322return Atomic::load(&_next);323}324325void ExceptionCache::set_next(ExceptionCache *ec) {326Atomic::store(&_next, ec);327}328329//-----------------------------------------------------------------------------330331332// Helper used by both find_pc_desc methods.333static inline bool match_desc(PcDesc* pc, int pc_offset, bool approximate) {334NOT_PRODUCT(++pc_nmethod_stats.pc_desc_tests);335if (!approximate)336return pc->pc_offset() == pc_offset;337else338return (pc-1)->pc_offset() < pc_offset && pc_offset <= pc->pc_offset();339}340341void PcDescCache::reset_to(PcDesc* initial_pc_desc) {342if (initial_pc_desc == NULL) {343_pc_descs[0] = NULL; // native method; no PcDescs at all344return;345}346NOT_PRODUCT(++pc_nmethod_stats.pc_desc_resets);347// reset the cache by filling it with benign (non-null) values348assert(initial_pc_desc->pc_offset() < 0, "must be sentinel");349for (int i = 0; i < cache_size; i++)350_pc_descs[i] = initial_pc_desc;351}352353PcDesc* PcDescCache::find_pc_desc(int pc_offset, bool approximate) {354NOT_PRODUCT(++pc_nmethod_stats.pc_desc_queries);355NOT_PRODUCT(if (approximate) ++pc_nmethod_stats.pc_desc_approx);356357// Note: one might think that caching the most recently358// read value separately would be a win, but one would be359// wrong. When many threads are updating it, the cache360// line it's in would bounce between caches, negating361// any benefit.362363// In order to prevent race conditions do not load cache elements364// repeatedly, but use a local copy:365PcDesc* res;366367// Step one: Check the most recently added value.368res = _pc_descs[0];369if (res == NULL) return NULL; // native method; no PcDescs at all370if (match_desc(res, pc_offset, approximate)) {371NOT_PRODUCT(++pc_nmethod_stats.pc_desc_repeats);372return res;373}374375// Step two: Check the rest of the LRU cache.376for (int i = 1; i < cache_size; ++i) {377res = _pc_descs[i];378if (res->pc_offset() < 0) break; // optimization: skip empty cache379if (match_desc(res, pc_offset, approximate)) {380NOT_PRODUCT(++pc_nmethod_stats.pc_desc_hits);381return res;382}383}384385// Report failure.386return NULL;387}388389void PcDescCache::add_pc_desc(PcDesc* pc_desc) {390NOT_PRODUCT(++pc_nmethod_stats.pc_desc_adds);391// Update the LRU cache by shifting pc_desc forward.392for (int i = 0; i < cache_size; i++) {393PcDesc* next = _pc_descs[i];394_pc_descs[i] = pc_desc;395pc_desc = next;396}397}398399// adjust pcs_size so that it is a multiple of both oopSize and400// sizeof(PcDesc) (assumes that if sizeof(PcDesc) is not a multiple401// of oopSize, then 2*sizeof(PcDesc) is)402static int adjust_pcs_size(int pcs_size) {403int nsize = align_up(pcs_size, oopSize);404if ((nsize % sizeof(PcDesc)) != 0) {405nsize = pcs_size + sizeof(PcDesc);406}407assert((nsize % oopSize) == 0, "correct alignment");408return nsize;409}410411412int nmethod::total_size() const {413return414consts_size() +415insts_size() +416stub_size() +417scopes_data_size() +418scopes_pcs_size() +419handler_table_size() +420nul_chk_table_size();421}422423address* nmethod::orig_pc_addr(const frame* fr) {424return (address*) ((address)fr->unextended_sp() + _orig_pc_offset);425}426427const char* nmethod::compile_kind() const {428if (is_osr_method()) return "osr";429if (method() != NULL && is_native_method()) return "c2n";430return NULL;431}432433// Fill in default values for various flag fields434void nmethod::init_defaults() {435_state = not_installed;436_has_flushed_dependencies = 0;437_lock_count = 0;438_stack_traversal_mark = 0;439_load_reported = false; // jvmti state440_unload_reported = false;441442#ifdef ASSERT443_oops_are_stale = false;444#endif445446_oops_do_mark_link = NULL;447_osr_link = NULL;448#if INCLUDE_RTM_OPT449_rtm_state = NoRTM;450#endif451}452453nmethod* nmethod::new_native_nmethod(const methodHandle& method,454int compile_id,455CodeBuffer *code_buffer,456int vep_offset,457int frame_complete,458int frame_size,459ByteSize basic_lock_owner_sp_offset,460ByteSize basic_lock_sp_offset,461OopMapSet* oop_maps) {462code_buffer->finalize_oop_references(method);463// create nmethod464nmethod* nm = NULL;465{466MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);467int native_nmethod_size = CodeBlob::allocation_size(code_buffer, sizeof(nmethod));468469CodeOffsets offsets;470offsets.set_value(CodeOffsets::Verified_Entry, vep_offset);471offsets.set_value(CodeOffsets::Frame_Complete, frame_complete);472nm = new (native_nmethod_size, CompLevel_none)473nmethod(method(), compiler_none, native_nmethod_size,474compile_id, &offsets,475code_buffer, frame_size,476basic_lock_owner_sp_offset,477basic_lock_sp_offset,478oop_maps);479NOT_PRODUCT(if (nm != NULL) native_nmethod_stats.note_native_nmethod(nm));480}481482if (nm != NULL) {483// verify nmethod484debug_only(nm->verify();) // might block485486nm->log_new_nmethod();487}488return nm;489}490491nmethod* nmethod::new_nmethod(const methodHandle& method,492int compile_id,493int entry_bci,494CodeOffsets* offsets,495int orig_pc_offset,496DebugInformationRecorder* debug_info,497Dependencies* dependencies,498CodeBuffer* code_buffer, int frame_size,499OopMapSet* oop_maps,500ExceptionHandlerTable* handler_table,501ImplicitExceptionTable* nul_chk_table,502AbstractCompiler* compiler,503int comp_level,504const GrowableArrayView<RuntimeStub*>& native_invokers505#if INCLUDE_JVMCI506, char* speculations,507int speculations_len,508int nmethod_mirror_index,509const char* nmethod_mirror_name,510FailedSpeculation** failed_speculations511#endif512)513{514assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");515code_buffer->finalize_oop_references(method);516// create nmethod517nmethod* nm = NULL;518{ MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);519#if INCLUDE_JVMCI520int jvmci_data_size = !compiler->is_jvmci() ? 0 : JVMCINMethodData::compute_size(nmethod_mirror_name);521#endif522int nmethod_size =523CodeBlob::allocation_size(code_buffer, sizeof(nmethod))524+ adjust_pcs_size(debug_info->pcs_size())525+ align_up((int)dependencies->size_in_bytes(), oopSize)526+ align_up(checked_cast<int>(native_invokers.data_size_in_bytes()), oopSize)527+ align_up(handler_table->size_in_bytes() , oopSize)528+ align_up(nul_chk_table->size_in_bytes() , oopSize)529#if INCLUDE_JVMCI530+ align_up(speculations_len , oopSize)531+ align_up(jvmci_data_size , oopSize)532#endif533+ align_up(debug_info->data_size() , oopSize);534535nm = new (nmethod_size, comp_level)536nmethod(method(), compiler->type(), nmethod_size, compile_id, entry_bci, offsets,537orig_pc_offset, debug_info, dependencies, code_buffer, frame_size,538oop_maps,539handler_table,540nul_chk_table,541compiler,542comp_level,543native_invokers544#if INCLUDE_JVMCI545, speculations,546speculations_len,547jvmci_data_size548#endif549);550551if (nm != NULL) {552#if INCLUDE_JVMCI553if (compiler->is_jvmci()) {554// Initialize the JVMCINMethodData object inlined into nm555nm->jvmci_nmethod_data()->initialize(nmethod_mirror_index, nmethod_mirror_name, failed_speculations);556}557#endif558// To make dependency checking during class loading fast, record559// the nmethod dependencies in the classes it is dependent on.560// This allows the dependency checking code to simply walk the561// class hierarchy above the loaded class, checking only nmethods562// which are dependent on those classes. The slow way is to563// check every nmethod for dependencies which makes it linear in564// the number of methods compiled. For applications with a lot565// classes the slow way is too slow.566for (Dependencies::DepStream deps(nm); deps.next(); ) {567if (deps.type() == Dependencies::call_site_target_value) {568// CallSite dependencies are managed on per-CallSite instance basis.569oop call_site = deps.argument_oop(0);570MethodHandles::add_dependent_nmethod(call_site, nm);571} else {572Klass* klass = deps.context_type();573if (klass == NULL) {574continue; // ignore things like evol_method575}576// record this nmethod as dependent on this klass577InstanceKlass::cast(klass)->add_dependent_nmethod(nm);578}579}580NOT_PRODUCT(if (nm != NULL) note_java_nmethod(nm));581}582}583// Do verification and logging outside CodeCache_lock.584if (nm != NULL) {585// Safepoints in nmethod::verify aren't allowed because nm hasn't been installed yet.586DEBUG_ONLY(nm->verify();)587nm->log_new_nmethod();588}589return nm;590}591592// For native wrappers593nmethod::nmethod(594Method* method,595CompilerType type,596int nmethod_size,597int compile_id,598CodeOffsets* offsets,599CodeBuffer* code_buffer,600int frame_size,601ByteSize basic_lock_owner_sp_offset,602ByteSize basic_lock_sp_offset,603OopMapSet* oop_maps )604: CompiledMethod(method, "native nmethod", type, nmethod_size, sizeof(nmethod), code_buffer, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps, false),605_is_unloading_state(0),606_native_receiver_sp_offset(basic_lock_owner_sp_offset),607_native_basic_lock_sp_offset(basic_lock_sp_offset)608{609{610int scopes_data_offset = 0;611int deoptimize_offset = 0;612int deoptimize_mh_offset = 0;613614debug_only(NoSafepointVerifier nsv;)615assert_locked_or_safepoint(CodeCache_lock);616617init_defaults();618_entry_bci = InvocationEntryBci;619// We have no exception handler or deopt handler make the620// values something that will never match a pc like the nmethod vtable entry621_exception_offset = 0;622_orig_pc_offset = 0;623624_consts_offset = data_offset();625_stub_offset = data_offset();626_oops_offset = data_offset();627_metadata_offset = _oops_offset + align_up(code_buffer->total_oop_size(), oopSize);628scopes_data_offset = _metadata_offset + align_up(code_buffer->total_metadata_size(), wordSize);629_scopes_pcs_offset = scopes_data_offset;630_dependencies_offset = _scopes_pcs_offset;631_native_invokers_offset = _dependencies_offset;632_handler_table_offset = _native_invokers_offset;633_nul_chk_table_offset = _handler_table_offset;634#if INCLUDE_JVMCI635_speculations_offset = _nul_chk_table_offset;636_jvmci_data_offset = _speculations_offset;637_nmethod_end_offset = _jvmci_data_offset;638#else639_nmethod_end_offset = _nul_chk_table_offset;640#endif641_compile_id = compile_id;642_comp_level = CompLevel_none;643_entry_point = code_begin() + offsets->value(CodeOffsets::Entry);644_verified_entry_point = code_begin() + offsets->value(CodeOffsets::Verified_Entry);645_osr_entry_point = NULL;646_exception_cache = NULL;647_pc_desc_container.reset_to(NULL);648_hotness_counter = NMethodSweeper::hotness_counter_reset_val();649650_scopes_data_begin = (address) this + scopes_data_offset;651_deopt_handler_begin = (address) this + deoptimize_offset;652_deopt_mh_handler_begin = (address) this + deoptimize_mh_offset;653654code_buffer->copy_code_and_locs_to(this);655code_buffer->copy_values_to(this);656657clear_unloading_state();658659Universe::heap()->register_nmethod(this);660debug_only(Universe::heap()->verify_nmethod(this));661662CodeCache::commit(this);663}664665if (PrintNativeNMethods || PrintDebugInfo || PrintRelocations || PrintDependencies) {666ttyLocker ttyl; // keep the following output all in one block667// This output goes directly to the tty, not the compiler log.668// To enable tools to match it up with the compilation activity,669// be sure to tag this tty output with the compile ID.670if (xtty != NULL) {671xtty->begin_head("print_native_nmethod");672xtty->method(_method);673xtty->stamp();674xtty->end_head(" address='" INTPTR_FORMAT "'", (intptr_t) this);675}676// Print the header part, then print the requested information.677// This is both handled in decode2(), called via print_code() -> decode()678if (PrintNativeNMethods) {679tty->print_cr("-------------------------- Assembly (native nmethod) ---------------------------");680print_code();681tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");682#if defined(SUPPORT_DATA_STRUCTS)683if (AbstractDisassembler::show_structs()) {684if (oop_maps != NULL) {685tty->print("oop maps:"); // oop_maps->print_on(tty) outputs a cr() at the beginning686oop_maps->print_on(tty);687tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");688}689}690#endif691} else {692print(); // print the header part only.693}694#if defined(SUPPORT_DATA_STRUCTS)695if (AbstractDisassembler::show_structs()) {696if (PrintRelocations) {697print_relocations();698tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");699}700}701#endif702if (xtty != NULL) {703xtty->tail("print_native_nmethod");704}705}706}707708void* nmethod::operator new(size_t size, int nmethod_size, int comp_level) throw () {709return CodeCache::allocate(nmethod_size, CodeCache::get_code_blob_type(comp_level));710}711712nmethod::nmethod(713Method* method,714CompilerType type,715int nmethod_size,716int compile_id,717int entry_bci,718CodeOffsets* offsets,719int orig_pc_offset,720DebugInformationRecorder* debug_info,721Dependencies* dependencies,722CodeBuffer *code_buffer,723int frame_size,724OopMapSet* oop_maps,725ExceptionHandlerTable* handler_table,726ImplicitExceptionTable* nul_chk_table,727AbstractCompiler* compiler,728int comp_level,729const GrowableArrayView<RuntimeStub*>& native_invokers730#if INCLUDE_JVMCI731, char* speculations,732int speculations_len,733int jvmci_data_size734#endif735)736: CompiledMethod(method, "nmethod", type, nmethod_size, sizeof(nmethod), code_buffer, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps, false),737_is_unloading_state(0),738_native_receiver_sp_offset(in_ByteSize(-1)),739_native_basic_lock_sp_offset(in_ByteSize(-1))740{741assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");742{743debug_only(NoSafepointVerifier nsv;)744assert_locked_or_safepoint(CodeCache_lock);745746_deopt_handler_begin = (address) this;747_deopt_mh_handler_begin = (address) this;748749init_defaults();750_entry_bci = entry_bci;751_compile_id = compile_id;752_comp_level = comp_level;753_orig_pc_offset = orig_pc_offset;754_hotness_counter = NMethodSweeper::hotness_counter_reset_val();755756// Section offsets757_consts_offset = content_offset() + code_buffer->total_offset_of(code_buffer->consts());758_stub_offset = content_offset() + code_buffer->total_offset_of(code_buffer->stubs());759set_ctable_begin(header_begin() + _consts_offset);760761#if INCLUDE_JVMCI762if (compiler->is_jvmci()) {763// JVMCI might not produce any stub sections764if (offsets->value(CodeOffsets::Exceptions) != -1) {765_exception_offset = code_offset() + offsets->value(CodeOffsets::Exceptions);766} else {767_exception_offset = -1;768}769if (offsets->value(CodeOffsets::Deopt) != -1) {770_deopt_handler_begin = (address) this + code_offset() + offsets->value(CodeOffsets::Deopt);771} else {772_deopt_handler_begin = NULL;773}774if (offsets->value(CodeOffsets::DeoptMH) != -1) {775_deopt_mh_handler_begin = (address) this + code_offset() + offsets->value(CodeOffsets::DeoptMH);776} else {777_deopt_mh_handler_begin = NULL;778}779} else780#endif781{782// Exception handler and deopt handler are in the stub section783assert(offsets->value(CodeOffsets::Exceptions) != -1, "must be set");784assert(offsets->value(CodeOffsets::Deopt ) != -1, "must be set");785786_exception_offset = _stub_offset + offsets->value(CodeOffsets::Exceptions);787_deopt_handler_begin = (address) this + _stub_offset + offsets->value(CodeOffsets::Deopt);788if (offsets->value(CodeOffsets::DeoptMH) != -1) {789_deopt_mh_handler_begin = (address) this + _stub_offset + offsets->value(CodeOffsets::DeoptMH);790} else {791_deopt_mh_handler_begin = NULL;792}793}794if (offsets->value(CodeOffsets::UnwindHandler) != -1) {795_unwind_handler_offset = code_offset() + offsets->value(CodeOffsets::UnwindHandler);796} else {797_unwind_handler_offset = -1;798}799800_oops_offset = data_offset();801_metadata_offset = _oops_offset + align_up(code_buffer->total_oop_size(), oopSize);802int scopes_data_offset = _metadata_offset + align_up(code_buffer->total_metadata_size(), wordSize);803804_scopes_pcs_offset = scopes_data_offset + align_up(debug_info->data_size (), oopSize);805_dependencies_offset = _scopes_pcs_offset + adjust_pcs_size(debug_info->pcs_size());806_native_invokers_offset = _dependencies_offset + align_up((int)dependencies->size_in_bytes(), oopSize);807_handler_table_offset = _native_invokers_offset + align_up(checked_cast<int>(native_invokers.data_size_in_bytes()), oopSize);808_nul_chk_table_offset = _handler_table_offset + align_up(handler_table->size_in_bytes(), oopSize);809#if INCLUDE_JVMCI810_speculations_offset = _nul_chk_table_offset + align_up(nul_chk_table->size_in_bytes(), oopSize);811_jvmci_data_offset = _speculations_offset + align_up(speculations_len, oopSize);812_nmethod_end_offset = _jvmci_data_offset + align_up(jvmci_data_size, oopSize);813#else814_nmethod_end_offset = _nul_chk_table_offset + align_up(nul_chk_table->size_in_bytes(), oopSize);815#endif816_entry_point = code_begin() + offsets->value(CodeOffsets::Entry);817_verified_entry_point = code_begin() + offsets->value(CodeOffsets::Verified_Entry);818_osr_entry_point = code_begin() + offsets->value(CodeOffsets::OSR_Entry);819_exception_cache = NULL;820_scopes_data_begin = (address) this + scopes_data_offset;821822_pc_desc_container.reset_to(scopes_pcs_begin());823824code_buffer->copy_code_and_locs_to(this);825// Copy contents of ScopeDescRecorder to nmethod826code_buffer->copy_values_to(this);827debug_info->copy_to(this);828dependencies->copy_to(this);829if (native_invokers.is_nonempty()) { // can not get address of zero-length array830// Copy native stubs831memcpy(native_invokers_begin(), native_invokers.adr_at(0), native_invokers.data_size_in_bytes());832}833clear_unloading_state();834835Universe::heap()->register_nmethod(this);836debug_only(Universe::heap()->verify_nmethod(this));837838CodeCache::commit(this);839840// Copy contents of ExceptionHandlerTable to nmethod841handler_table->copy_to(this);842nul_chk_table->copy_to(this);843844#if INCLUDE_JVMCI845// Copy speculations to nmethod846if (speculations_size() != 0) {847memcpy(speculations_begin(), speculations, speculations_len);848}849#endif850851// we use the information of entry points to find out if a method is852// static or non static853assert(compiler->is_c2() || compiler->is_jvmci() ||854_method->is_static() == (entry_point() == _verified_entry_point),855" entry points must be same for static methods and vice versa");856}857}858859// Print a short set of xml attributes to identify this nmethod. The860// output should be embedded in some other element.861void nmethod::log_identity(xmlStream* log) const {862log->print(" compile_id='%d'", compile_id());863const char* nm_kind = compile_kind();864if (nm_kind != NULL) log->print(" compile_kind='%s'", nm_kind);865log->print(" compiler='%s'", compiler_name());866if (TieredCompilation) {867log->print(" level='%d'", comp_level());868}869#if INCLUDE_JVMCI870if (jvmci_nmethod_data() != NULL) {871const char* jvmci_name = jvmci_nmethod_data()->name();872if (jvmci_name != NULL) {873log->print(" jvmci_mirror_name='");874log->text("%s", jvmci_name);875log->print("'");876}877}878#endif879}880881882#define LOG_OFFSET(log, name) \883if (p2i(name##_end()) - p2i(name##_begin())) \884log->print(" " XSTR(name) "_offset='" INTX_FORMAT "'" , \885p2i(name##_begin()) - p2i(this))886887888void nmethod::log_new_nmethod() const {889if (LogCompilation && xtty != NULL) {890ttyLocker ttyl;891xtty->begin_elem("nmethod");892log_identity(xtty);893xtty->print(" entry='" INTPTR_FORMAT "' size='%d'", p2i(code_begin()), size());894xtty->print(" address='" INTPTR_FORMAT "'", p2i(this));895896LOG_OFFSET(xtty, relocation);897LOG_OFFSET(xtty, consts);898LOG_OFFSET(xtty, insts);899LOG_OFFSET(xtty, stub);900LOG_OFFSET(xtty, scopes_data);901LOG_OFFSET(xtty, scopes_pcs);902LOG_OFFSET(xtty, dependencies);903LOG_OFFSET(xtty, handler_table);904LOG_OFFSET(xtty, nul_chk_table);905LOG_OFFSET(xtty, oops);906LOG_OFFSET(xtty, metadata);907908xtty->method(method());909xtty->stamp();910xtty->end_elem();911}912}913914#undef LOG_OFFSET915916917// Print out more verbose output usually for a newly created nmethod.918void nmethod::print_on(outputStream* st, const char* msg) const {919if (st != NULL) {920ttyLocker ttyl;921if (WizardMode) {922CompileTask::print(st, this, msg, /*short_form:*/ true);923st->print_cr(" (" INTPTR_FORMAT ")", p2i(this));924} else {925CompileTask::print(st, this, msg, /*short_form:*/ false);926}927}928}929930void nmethod::maybe_print_nmethod(DirectiveSet* directive) {931bool printnmethods = directive->PrintAssemblyOption || directive->PrintNMethodsOption;932if (printnmethods || PrintDebugInfo || PrintRelocations || PrintDependencies || PrintExceptionHandlers) {933print_nmethod(printnmethods);934}935}936937void nmethod::print_nmethod(bool printmethod) {938run_nmethod_entry_barrier(); // ensure all embedded OOPs are valid before printing939940ttyLocker ttyl; // keep the following output all in one block941if (xtty != NULL) {942xtty->begin_head("print_nmethod");943log_identity(xtty);944xtty->stamp();945xtty->end_head();946}947// Print the header part, then print the requested information.948// This is both handled in decode2().949if (printmethod) {950ResourceMark m;951if (is_compiled_by_c1()) {952tty->cr();953tty->print_cr("============================= C1-compiled nmethod ==============================");954}955if (is_compiled_by_jvmci()) {956tty->cr();957tty->print_cr("=========================== JVMCI-compiled nmethod =============================");958}959tty->print_cr("----------------------------------- Assembly -----------------------------------");960decode2(tty);961#if defined(SUPPORT_DATA_STRUCTS)962if (AbstractDisassembler::show_structs()) {963// Print the oops from the underlying CodeBlob as well.964tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");965print_oops(tty);966tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");967print_metadata(tty);968tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");969print_pcs();970tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");971if (oop_maps() != NULL) {972tty->print("oop maps:"); // oop_maps()->print_on(tty) outputs a cr() at the beginning973oop_maps()->print_on(tty);974tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");975}976}977#endif978} else {979print(); // print the header part only.980}981982#if defined(SUPPORT_DATA_STRUCTS)983if (AbstractDisassembler::show_structs()) {984methodHandle mh(Thread::current(), _method);985if (printmethod || PrintDebugInfo || CompilerOracle::has_option(mh, CompileCommand::PrintDebugInfo)) {986print_scopes();987tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");988}989if (printmethod || PrintRelocations || CompilerOracle::has_option(mh, CompileCommand::PrintRelocations)) {990print_relocations();991tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");992}993if (printmethod || PrintDependencies || CompilerOracle::has_option(mh, CompileCommand::PrintDependencies)) {994print_dependencies();995tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");996}997if (printmethod && native_invokers_begin() < native_invokers_end()) {998print_native_invokers();999tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");1000}1001if (printmethod || PrintExceptionHandlers) {1002print_handler_table();1003tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");1004print_nul_chk_table();1005tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");1006}10071008if (printmethod) {1009print_recorded_oops();1010tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");1011print_recorded_metadata();1012tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");1013}1014}1015#endif10161017if (xtty != NULL) {1018xtty->tail("print_nmethod");1019}1020}102110221023// Promote one word from an assembly-time handle to a live embedded oop.1024inline void nmethod::initialize_immediate_oop(oop* dest, jobject handle) {1025if (handle == NULL ||1026// As a special case, IC oops are initialized to 1 or -1.1027handle == (jobject) Universe::non_oop_word()) {1028*(void**)dest = handle;1029} else {1030*dest = JNIHandles::resolve_non_null(handle);1031}1032}103310341035// Have to have the same name because it's called by a template1036void nmethod::copy_values(GrowableArray<jobject>* array) {1037int length = array->length();1038assert((address)(oops_begin() + length) <= (address)oops_end(), "oops big enough");1039oop* dest = oops_begin();1040for (int index = 0 ; index < length; index++) {1041initialize_immediate_oop(&dest[index], array->at(index));1042}10431044// Now we can fix up all the oops in the code. We need to do this1045// in the code because the assembler uses jobjects as placeholders.1046// The code and relocations have already been initialized by the1047// CodeBlob constructor, so it is valid even at this early point to1048// iterate over relocations and patch the code.1049fix_oop_relocations(NULL, NULL, /*initialize_immediates=*/ true);1050}10511052void nmethod::copy_values(GrowableArray<Metadata*>* array) {1053int length = array->length();1054assert((address)(metadata_begin() + length) <= (address)metadata_end(), "big enough");1055Metadata** dest = metadata_begin();1056for (int index = 0 ; index < length; index++) {1057dest[index] = array->at(index);1058}1059}10601061void nmethod::free_native_invokers() {1062for (RuntimeStub** it = native_invokers_begin(); it < native_invokers_end(); it++) {1063CodeCache::free(*it);1064}1065}10661067void nmethod::fix_oop_relocations(address begin, address end, bool initialize_immediates) {1068// re-patch all oop-bearing instructions, just in case some oops moved1069RelocIterator iter(this, begin, end);1070while (iter.next()) {1071if (iter.type() == relocInfo::oop_type) {1072oop_Relocation* reloc = iter.oop_reloc();1073if (initialize_immediates && reloc->oop_is_immediate()) {1074oop* dest = reloc->oop_addr();1075initialize_immediate_oop(dest, cast_from_oop<jobject>(*dest));1076}1077// Refresh the oop-related bits of this instruction.1078reloc->fix_oop_relocation();1079} else if (iter.type() == relocInfo::metadata_type) {1080metadata_Relocation* reloc = iter.metadata_reloc();1081reloc->fix_metadata_relocation();1082}1083}1084}108510861087void nmethod::verify_clean_inline_caches() {1088assert(CompiledICLocker::is_safe(this), "mt unsafe call");10891090ResourceMark rm;1091RelocIterator iter(this, oops_reloc_begin());1092while(iter.next()) {1093switch(iter.type()) {1094case relocInfo::virtual_call_type:1095case relocInfo::opt_virtual_call_type: {1096CompiledIC *ic = CompiledIC_at(&iter);1097// Ok, to lookup references to zombies here1098CodeBlob *cb = CodeCache::find_blob_unsafe(ic->ic_destination());1099assert(cb != NULL, "destination not in CodeBlob?");1100nmethod* nm = cb->as_nmethod_or_null();1101if( nm != NULL ) {1102// Verify that inline caches pointing to both zombie and not_entrant methods are clean1103if (!nm->is_in_use() || (nm->method()->code() != nm)) {1104assert(ic->is_clean(), "IC should be clean");1105}1106}1107break;1108}1109case relocInfo::static_call_type: {1110CompiledStaticCall *csc = compiledStaticCall_at(iter.reloc());1111CodeBlob *cb = CodeCache::find_blob_unsafe(csc->destination());1112assert(cb != NULL, "destination not in CodeBlob?");1113nmethod* nm = cb->as_nmethod_or_null();1114if( nm != NULL ) {1115// Verify that inline caches pointing to both zombie and not_entrant methods are clean1116if (!nm->is_in_use() || (nm->method()->code() != nm)) {1117assert(csc->is_clean(), "IC should be clean");1118}1119}1120break;1121}1122default:1123break;1124}1125}1126}11271128// This is a private interface with the sweeper.1129void nmethod::mark_as_seen_on_stack() {1130assert(is_alive(), "Must be an alive method");1131// Set the traversal mark to ensure that the sweeper does 21132// cleaning passes before moving to zombie.1133set_stack_traversal_mark(NMethodSweeper::traversal_count());1134}11351136// Tell if a non-entrant method can be converted to a zombie (i.e.,1137// there are no activations on the stack, not in use by the VM,1138// and not in use by the ServiceThread)1139bool nmethod::can_convert_to_zombie() {1140// Note that this is called when the sweeper has observed the nmethod to be1141// not_entrant. However, with concurrent code cache unloading, the state1142// might have moved on to unloaded if it is_unloading(), due to racing1143// concurrent GC threads.1144assert(is_not_entrant() || is_unloading() ||1145!Thread::current()->is_Code_cache_sweeper_thread(),1146"must be a non-entrant method if called from sweeper");11471148// Since the nmethod sweeper only does partial sweep the sweeper's traversal1149// count can be greater than the stack traversal count before it hits the1150// nmethod for the second time.1151// If an is_unloading() nmethod is still not_entrant, then it is not safe to1152// convert it to zombie due to GC unloading interactions. However, if it1153// has become unloaded, then it is okay to convert such nmethods to zombie.1154return stack_traversal_mark() + 1 < NMethodSweeper::traversal_count() &&1155!is_locked_by_vm() && (!is_unloading() || is_unloaded());1156}11571158void nmethod::inc_decompile_count() {1159if (!is_compiled_by_c2() && !is_compiled_by_jvmci()) return;1160// Could be gated by ProfileTraps, but do not bother...1161Method* m = method();1162if (m == NULL) return;1163MethodData* mdo = m->method_data();1164if (mdo == NULL) return;1165// There is a benign race here. See comments in methodData.hpp.1166mdo->inc_decompile_count();1167}11681169bool nmethod::try_transition(int new_state_int) {1170signed char new_state = new_state_int;1171#ifdef ASSERT1172if (new_state != unloaded) {1173assert_lock_strong(CompiledMethod_lock);1174}1175#endif1176for (;;) {1177signed char old_state = Atomic::load(&_state);1178if (old_state >= new_state) {1179// Ensure monotonicity of transitions.1180return false;1181}1182if (Atomic::cmpxchg(&_state, old_state, new_state) == old_state) {1183return true;1184}1185}1186}11871188void nmethod::make_unloaded() {1189post_compiled_method_unload();11901191// This nmethod is being unloaded, make sure that dependencies1192// recorded in instanceKlasses get flushed.1193// Since this work is being done during a GC, defer deleting dependencies from the1194// InstanceKlass.1195assert(Universe::heap()->is_gc_active() || Thread::current()->is_ConcurrentGC_thread(),1196"should only be called during gc");1197flush_dependencies(/*delete_immediately*/false);11981199// Break cycle between nmethod & method1200LogTarget(Trace, class, unload, nmethod) lt;1201if (lt.is_enabled()) {1202LogStream ls(lt);1203ls.print("making nmethod " INTPTR_FORMAT1204" unloadable, Method*(" INTPTR_FORMAT1205") ",1206p2i(this), p2i(_method));1207ls.cr();1208}1209// Unlink the osr method, so we do not look this up again1210if (is_osr_method()) {1211// Invalidate the osr nmethod only once. Note that with concurrent1212// code cache unloading, OSR nmethods are invalidated before they1213// are made unloaded. Therefore, this becomes a no-op then.1214if (is_in_use()) {1215invalidate_osr_method();1216}1217#ifdef ASSERT1218if (method() != NULL) {1219// Make sure osr nmethod is invalidated, i.e. not on the list1220bool found = method()->method_holder()->remove_osr_nmethod(this);1221assert(!found, "osr nmethod should have been invalidated");1222}1223#endif1224}12251226// If _method is already NULL the Method* is about to be unloaded,1227// so we don't have to break the cycle. Note that it is possible to1228// have the Method* live here, in case we unload the nmethod because1229// it is pointing to some oop (other than the Method*) being unloaded.1230if (_method != NULL) {1231_method->unlink_code(this);1232}12331234// Make the class unloaded - i.e., change state and notify sweeper1235assert(SafepointSynchronize::is_at_safepoint() || Thread::current()->is_ConcurrentGC_thread(),1236"must be at safepoint");12371238{1239// Clear ICStubs and release any CompiledICHolders.1240CompiledICLocker ml(this);1241clear_ic_callsites();1242}12431244// Unregister must be done before the state change1245{1246MutexLocker ml(SafepointSynchronize::is_at_safepoint() ? NULL : CodeCache_lock,1247Mutex::_no_safepoint_check_flag);1248Universe::heap()->unregister_nmethod(this);1249}12501251// Clear the method of this dead nmethod1252set_method(NULL);12531254// Log the unloading.1255log_state_change();12561257// The Method* is gone at this point1258assert(_method == NULL, "Tautology");12591260set_osr_link(NULL);1261NMethodSweeper::report_state_change(this);12621263bool transition_success = try_transition(unloaded);12641265// It is an important invariant that there exists no race between1266// the sweeper and GC thread competing for making the same nmethod1267// zombie and unloaded respectively. This is ensured by1268// can_convert_to_zombie() returning false for any is_unloading()1269// nmethod, informing the sweeper not to step on any GC toes.1270assert(transition_success, "Invalid nmethod transition to unloaded");12711272#if INCLUDE_JVMCI1273// Clear the link between this nmethod and a HotSpotNmethod mirror1274JVMCINMethodData* nmethod_data = jvmci_nmethod_data();1275if (nmethod_data != NULL) {1276nmethod_data->invalidate_nmethod_mirror(this);1277}1278#endif1279}12801281void nmethod::invalidate_osr_method() {1282assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod");1283// Remove from list of active nmethods1284if (method() != NULL) {1285method()->method_holder()->remove_osr_nmethod(this);1286}1287}12881289void nmethod::log_state_change() const {1290if (LogCompilation) {1291if (xtty != NULL) {1292ttyLocker ttyl; // keep the following output all in one block1293if (_state == unloaded) {1294xtty->begin_elem("make_unloaded thread='" UINTX_FORMAT "'",1295os::current_thread_id());1296} else {1297xtty->begin_elem("make_not_entrant thread='" UINTX_FORMAT "'%s",1298os::current_thread_id(),1299(_state == zombie ? " zombie='1'" : ""));1300}1301log_identity(xtty);1302xtty->stamp();1303xtty->end_elem();1304}1305}13061307const char *state_msg = _state == zombie ? "made zombie" : "made not entrant";1308CompileTask::print_ul(this, state_msg);1309if (PrintCompilation && _state != unloaded) {1310print_on(tty, state_msg);1311}1312}13131314void nmethod::unlink_from_method() {1315if (method() != NULL) {1316method()->unlink_code(this);1317}1318}13191320/**1321* Common functionality for both make_not_entrant and make_zombie1322*/1323bool nmethod::make_not_entrant_or_zombie(int state) {1324assert(state == zombie || state == not_entrant, "must be zombie or not_entrant");13251326if (Atomic::load(&_state) >= state) {1327// Avoid taking the lock if already in required state.1328// This is safe from races because the state is an end-state,1329// which the nmethod cannot back out of once entered.1330// No need for fencing either.1331return false;1332}13331334// Make sure the nmethod is not flushed.1335nmethodLocker nml(this);1336// This can be called while the system is already at a safepoint which is ok1337NoSafepointVerifier nsv;13381339// during patching, depending on the nmethod state we must notify the GC that1340// code has been unloaded, unregistering it. We cannot do this right while1341// holding the CompiledMethod_lock because we need to use the CodeCache_lock. This1342// would be prone to deadlocks.1343// This flag is used to remember whether we need to later lock and unregister.1344bool nmethod_needs_unregister = false;13451346{1347// Enter critical section. Does not block for safepoint.1348MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock, Mutex::_no_safepoint_check_flag);13491350// This logic is equivalent to the logic below for patching the1351// verified entry point of regular methods. We check that the1352// nmethod is in use to ensure that it is invalidated only once.1353if (is_osr_method() && is_in_use()) {1354// this effectively makes the osr nmethod not entrant1355invalidate_osr_method();1356}13571358if (Atomic::load(&_state) >= state) {1359// another thread already performed this transition so nothing1360// to do, but return false to indicate this.1361return false;1362}13631364// The caller can be calling the method statically or through an inline1365// cache call.1366if (!is_osr_method() && !is_not_entrant()) {1367NativeJump::patch_verified_entry(entry_point(), verified_entry_point(),1368SharedRuntime::get_handle_wrong_method_stub());1369}13701371if (is_in_use() && update_recompile_counts()) {1372// It's a true state change, so mark the method as decompiled.1373// Do it only for transition from alive.1374inc_decompile_count();1375}13761377// If the state is becoming a zombie, signal to unregister the nmethod with1378// the heap.1379// This nmethod may have already been unloaded during a full GC.1380if ((state == zombie) && !is_unloaded()) {1381nmethod_needs_unregister = true;1382}13831384// Must happen before state change. Otherwise we have a race condition in1385// nmethod::can_convert_to_zombie(). I.e., a method can immediately1386// transition its state from 'not_entrant' to 'zombie' without having to wait1387// for stack scanning.1388if (state == not_entrant) {1389mark_as_seen_on_stack();1390OrderAccess::storestore(); // _stack_traversal_mark and _state1391}13921393// Change state1394if (!try_transition(state)) {1395// If the transition fails, it is due to another thread making the nmethod more1396// dead. In particular, one thread might be making the nmethod unloaded concurrently.1397// If so, having patched in the jump in the verified entry unnecessarily is fine.1398// The nmethod is no longer possible to call by Java threads.1399// Incrementing the decompile count is also fine as the caller of make_not_entrant()1400// had a valid reason to deoptimize the nmethod.1401// Marking the nmethod as seen on stack also has no effect, as the nmethod is now1402// !is_alive(), and the seen on stack value is only used to convert not_entrant1403// nmethods to zombie in can_convert_to_zombie().1404return false;1405}14061407// Log the transition once1408log_state_change();14091410// Remove nmethod from method.1411unlink_from_method();14121413} // leave critical region under CompiledMethod_lock14141415#if INCLUDE_JVMCI1416// Invalidate can't occur while holding the Patching lock1417JVMCINMethodData* nmethod_data = jvmci_nmethod_data();1418if (nmethod_data != NULL) {1419nmethod_data->invalidate_nmethod_mirror(this);1420}1421#endif14221423#ifdef ASSERT1424if (is_osr_method() && method() != NULL) {1425// Make sure osr nmethod is invalidated, i.e. not on the list1426bool found = method()->method_holder()->remove_osr_nmethod(this);1427assert(!found, "osr nmethod should have been invalidated");1428}1429#endif14301431// When the nmethod becomes zombie it is no longer alive so the1432// dependencies must be flushed. nmethods in the not_entrant1433// state will be flushed later when the transition to zombie1434// happens or they get unloaded.1435if (state == zombie) {1436{1437// Flushing dependencies must be done before any possible1438// safepoint can sneak in, otherwise the oops used by the1439// dependency logic could have become stale.1440MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);1441if (nmethod_needs_unregister) {1442Universe::heap()->unregister_nmethod(this);1443}1444flush_dependencies(/*delete_immediately*/true);1445}14461447#if INCLUDE_JVMCI1448// Now that the nmethod has been unregistered, it's1449// safe to clear the HotSpotNmethod mirror oop.1450if (nmethod_data != NULL) {1451nmethod_data->clear_nmethod_mirror(this);1452}1453#endif14541455// Clear ICStubs to prevent back patching stubs of zombie or flushed1456// nmethods during the next safepoint (see ICStub::finalize), as well1457// as to free up CompiledICHolder resources.1458{1459CompiledICLocker ml(this);1460clear_ic_callsites();1461}14621463// zombie only - if a JVMTI agent has enabled the CompiledMethodUnload1464// event and it hasn't already been reported for this nmethod then1465// report it now. The event may have been reported earlier if the GC1466// marked it for unloading). JvmtiDeferredEventQueue support means1467// we no longer go to a safepoint here.1468post_compiled_method_unload();14691470#ifdef ASSERT1471// It's no longer safe to access the oops section since zombie1472// nmethods aren't scanned for GC.1473_oops_are_stale = true;1474#endif1475// the Method may be reclaimed by class unloading now that the1476// nmethod is in zombie state1477set_method(NULL);1478} else {1479assert(state == not_entrant, "other cases may need to be handled differently");1480}14811482if (TraceCreateZombies && state == zombie) {1483ResourceMark m;1484tty->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");1485}14861487NMethodSweeper::report_state_change(this);1488return true;1489}14901491void nmethod::flush() {1492MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);1493// Note that there are no valid oops in the nmethod anymore.1494assert(!is_osr_method() || is_unloaded() || is_zombie(),1495"osr nmethod must be unloaded or zombie before flushing");1496assert(is_zombie() || is_osr_method(), "must be a zombie method");1497assert (!is_locked_by_vm(), "locked methods shouldn't be flushed");1498assert_locked_or_safepoint(CodeCache_lock);14991500// completely deallocate this method1501Events::log(JavaThread::current(), "flushing nmethod " INTPTR_FORMAT, p2i(this));1502if (PrintMethodFlushing) {1503tty->print_cr("*flushing %s nmethod %3d/" INTPTR_FORMAT ". Live blobs:" UINT32_FORMAT1504"/Free CodeCache:" SIZE_FORMAT "Kb",1505is_osr_method() ? "osr" : "",_compile_id, p2i(this), CodeCache::blob_count(),1506CodeCache::unallocated_capacity(CodeCache::get_code_blob_type(this))/1024);1507}15081509// We need to deallocate any ExceptionCache data.1510// Note that we do not need to grab the nmethod lock for this, it1511// better be thread safe if we're disposing of it!1512ExceptionCache* ec = exception_cache();1513set_exception_cache(NULL);1514while(ec != NULL) {1515ExceptionCache* next = ec->next();1516delete ec;1517ec = next;1518}15191520Universe::heap()->flush_nmethod(this);1521CodeCache::unregister_old_nmethod(this);15221523CodeBlob::flush();1524CodeCache::free(this);1525}15261527oop nmethod::oop_at(int index) const {1528if (index == 0) {1529return NULL;1530}1531return NativeAccess<AS_NO_KEEPALIVE>::oop_load(oop_addr_at(index));1532}15331534oop nmethod::oop_at_phantom(int index) const {1535if (index == 0) {1536return NULL;1537}1538return NativeAccess<ON_PHANTOM_OOP_REF>::oop_load(oop_addr_at(index));1539}15401541//1542// Notify all classes this nmethod is dependent on that it is no1543// longer dependent. This should only be called in two situations.1544// First, when a nmethod transitions to a zombie all dependents need1545// to be clear. Since zombification happens at a safepoint there's no1546// synchronization issues. The second place is a little more tricky.1547// During phase 1 of mark sweep class unloading may happen and as a1548// result some nmethods may get unloaded. In this case the flushing1549// of dependencies must happen during phase 1 since after GC any1550// dependencies in the unloaded nmethod won't be updated, so1551// traversing the dependency information in unsafe. In that case this1552// function is called with a boolean argument and this function only1553// notifies instanceKlasses that are reachable15541555void nmethod::flush_dependencies(bool delete_immediately) {1556DEBUG_ONLY(bool called_by_gc = Universe::heap()->is_gc_active() || Thread::current()->is_ConcurrentGC_thread();)1557assert(called_by_gc != delete_immediately,1558"delete_immediately is false if and only if we are called during GC");1559if (!has_flushed_dependencies()) {1560set_has_flushed_dependencies();1561for (Dependencies::DepStream deps(this); deps.next(); ) {1562if (deps.type() == Dependencies::call_site_target_value) {1563// CallSite dependencies are managed on per-CallSite instance basis.1564oop call_site = deps.argument_oop(0);1565if (delete_immediately) {1566assert_locked_or_safepoint(CodeCache_lock);1567MethodHandles::remove_dependent_nmethod(call_site, this);1568} else {1569MethodHandles::clean_dependency_context(call_site);1570}1571} else {1572Klass* klass = deps.context_type();1573if (klass == NULL) {1574continue; // ignore things like evol_method1575}1576// During GC delete_immediately is false, and liveness1577// of dependee determines class that needs to be updated.1578if (delete_immediately) {1579assert_locked_or_safepoint(CodeCache_lock);1580InstanceKlass::cast(klass)->remove_dependent_nmethod(this);1581} else if (klass->is_loader_alive()) {1582// The GC may clean dependency contexts concurrently and in parallel.1583InstanceKlass::cast(klass)->clean_dependency_context();1584}1585}1586}1587}1588}15891590// ------------------------------------------------------------------1591// post_compiled_method_load_event1592// new method for install_code() path1593// Transfer information from compilation to jvmti1594void nmethod::post_compiled_method_load_event(JvmtiThreadState* state) {15951596// Don't post this nmethod load event if it is already dying1597// because the sweeper might already be deleting this nmethod.1598if (is_not_entrant() && can_convert_to_zombie()) {1599return;1600}16011602// This is a bad time for a safepoint. We don't want1603// this nmethod to get unloaded while we're queueing the event.1604NoSafepointVerifier nsv;16051606Method* m = method();1607HOTSPOT_COMPILED_METHOD_LOAD(1608(char *) m->klass_name()->bytes(),1609m->klass_name()->utf8_length(),1610(char *) m->name()->bytes(),1611m->name()->utf8_length(),1612(char *) m->signature()->bytes(),1613m->signature()->utf8_length(),1614insts_begin(), insts_size());161516161617if (JvmtiExport::should_post_compiled_method_load()) {1618// Only post unload events if load events are found.1619set_load_reported();1620// If a JavaThread hasn't been passed in, let the Service thread1621// (which is a real Java thread) post the event1622JvmtiDeferredEvent event = JvmtiDeferredEvent::compiled_method_load_event(this);1623if (state == NULL) {1624// Execute any barrier code for this nmethod as if it's called, since1625// keeping it alive looks like stack walking.1626run_nmethod_entry_barrier();1627ServiceThread::enqueue_deferred_event(&event);1628} else {1629// This enters the nmethod barrier outside in the caller.1630state->enqueue_event(&event);1631}1632}1633}16341635void nmethod::post_compiled_method_unload() {1636if (unload_reported()) {1637// During unloading we transition to unloaded and then to zombie1638// and the unloading is reported during the first transition.1639return;1640}16411642assert(_method != NULL && !is_unloaded(), "just checking");1643DTRACE_METHOD_UNLOAD_PROBE(method());16441645// If a JVMTI agent has enabled the CompiledMethodUnload event then1646// post the event. Sometime later this nmethod will be made a zombie1647// by the sweeper but the Method* will not be valid at that point.1648// The jmethodID is a weak reference to the Method* so if1649// it's being unloaded there's no way to look it up since the weak1650// ref will have been cleared.16511652// Don't bother posting the unload if the load event wasn't posted.1653if (load_reported() && JvmtiExport::should_post_compiled_method_unload()) {1654assert(!unload_reported(), "already unloaded");1655JvmtiDeferredEvent event =1656JvmtiDeferredEvent::compiled_method_unload_event(1657method()->jmethod_id(), insts_begin());1658ServiceThread::enqueue_deferred_event(&event);1659}16601661// The JVMTI CompiledMethodUnload event can be enabled or disabled at1662// any time. As the nmethod is being unloaded now we mark it has1663// having the unload event reported - this will ensure that we don't1664// attempt to report the event in the unlikely scenario where the1665// event is enabled at the time the nmethod is made a zombie.1666set_unload_reported();1667}16681669// Iterate over metadata calling this function. Used by RedefineClasses1670void nmethod::metadata_do(MetadataClosure* f) {1671{1672// Visit all immediate references that are embedded in the instruction stream.1673RelocIterator iter(this, oops_reloc_begin());1674while (iter.next()) {1675if (iter.type() == relocInfo::metadata_type) {1676metadata_Relocation* r = iter.metadata_reloc();1677// In this metadata, we must only follow those metadatas directly embedded in1678// the code. Other metadatas (oop_index>0) are seen as part of1679// the metadata section below.1680assert(1 == (r->metadata_is_immediate()) +1681(r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()),1682"metadata must be found in exactly one place");1683if (r->metadata_is_immediate() && r->metadata_value() != NULL) {1684Metadata* md = r->metadata_value();1685if (md != _method) f->do_metadata(md);1686}1687} else if (iter.type() == relocInfo::virtual_call_type) {1688// Check compiledIC holders associated with this nmethod1689ResourceMark rm;1690CompiledIC *ic = CompiledIC_at(&iter);1691if (ic->is_icholder_call()) {1692CompiledICHolder* cichk = ic->cached_icholder();1693f->do_metadata(cichk->holder_metadata());1694f->do_metadata(cichk->holder_klass());1695} else {1696Metadata* ic_oop = ic->cached_metadata();1697if (ic_oop != NULL) {1698f->do_metadata(ic_oop);1699}1700}1701}1702}1703}17041705// Visit the metadata section1706for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {1707if (*p == Universe::non_oop_word() || *p == NULL) continue; // skip non-oops1708Metadata* md = *p;1709f->do_metadata(md);1710}17111712// Visit metadata not embedded in the other places.1713if (_method != NULL) f->do_metadata(_method);1714}17151716// The _is_unloading_state encodes a tuple comprising the unloading cycle1717// and the result of IsUnloadingBehaviour::is_unloading() fpr that cycle.1718// This is the bit layout of the _is_unloading_state byte: 00000CCU1719// CC refers to the cycle, which has 2 bits, and U refers to the result of1720// IsUnloadingBehaviour::is_unloading() for that unloading cycle.17211722class IsUnloadingState: public AllStatic {1723static const uint8_t _is_unloading_mask = 1;1724static const uint8_t _is_unloading_shift = 0;1725static const uint8_t _unloading_cycle_mask = 6;1726static const uint8_t _unloading_cycle_shift = 1;17271728static uint8_t set_is_unloading(uint8_t state, bool value) {1729state &= ~_is_unloading_mask;1730if (value) {1731state |= 1 << _is_unloading_shift;1732}1733assert(is_unloading(state) == value, "unexpected unloading cycle overflow");1734return state;1735}17361737static uint8_t set_unloading_cycle(uint8_t state, uint8_t value) {1738state &= ~_unloading_cycle_mask;1739state |= value << _unloading_cycle_shift;1740assert(unloading_cycle(state) == value, "unexpected unloading cycle overflow");1741return state;1742}17431744public:1745static bool is_unloading(uint8_t state) { return (state & _is_unloading_mask) >> _is_unloading_shift == 1; }1746static uint8_t unloading_cycle(uint8_t state) { return (state & _unloading_cycle_mask) >> _unloading_cycle_shift; }17471748static uint8_t create(bool is_unloading, uint8_t unloading_cycle) {1749uint8_t state = 0;1750state = set_is_unloading(state, is_unloading);1751state = set_unloading_cycle(state, unloading_cycle);1752return state;1753}1754};17551756bool nmethod::is_unloading() {1757uint8_t state = RawAccess<MO_RELAXED>::load(&_is_unloading_state);1758bool state_is_unloading = IsUnloadingState::is_unloading(state);1759if (state_is_unloading) {1760return true;1761}1762uint8_t state_unloading_cycle = IsUnloadingState::unloading_cycle(state);1763uint8_t current_cycle = CodeCache::unloading_cycle();1764if (state_unloading_cycle == current_cycle) {1765return false;1766}17671768// The IsUnloadingBehaviour is responsible for checking if there are any dead1769// oops in the CompiledMethod, by calling oops_do on it.1770state_unloading_cycle = current_cycle;17711772if (is_zombie()) {1773// Zombies without calculated unloading epoch are never unloading due to GC.17741775// There are no races where a previously observed is_unloading() nmethod1776// suddenly becomes not is_unloading() due to here being observed as zombie.17771778// With STW unloading, all is_alive() && is_unloading() nmethods are unlinked1779// and unloaded in the safepoint. That makes races where an nmethod is first1780// observed as is_alive() && is_unloading() and subsequently observed as1781// is_zombie() impossible.17821783// With concurrent unloading, all references to is_unloading() nmethods are1784// first unlinked (e.g. IC caches and dependency contexts). Then a global1785// handshake operation is performed with all JavaThreads before finally1786// unloading the nmethods. The sweeper never converts is_alive() && is_unloading()1787// nmethods to zombies; it waits for them to become is_unloaded(). So before1788// the global handshake, it is impossible for is_unloading() nmethods to1789// racingly become is_zombie(). And is_unloading() is calculated for all is_alive()1790// nmethods before taking that global handshake, meaning that it will never1791// be recalculated after the handshake.17921793// After that global handshake, is_unloading() nmethods are only observable1794// to the iterators, and they will never trigger recomputation of the cached1795// is_unloading_state, and hence may not suffer from such races.17961797state_is_unloading = false;1798} else {1799state_is_unloading = IsUnloadingBehaviour::current()->is_unloading(this);1800}18011802state = IsUnloadingState::create(state_is_unloading, state_unloading_cycle);18031804RawAccess<MO_RELAXED>::store(&_is_unloading_state, state);18051806return state_is_unloading;1807}18081809void nmethod::clear_unloading_state() {1810uint8_t state = IsUnloadingState::create(false, CodeCache::unloading_cycle());1811RawAccess<MO_RELAXED>::store(&_is_unloading_state, state);1812}181318141815// This is called at the end of the strong tracing/marking phase of a1816// GC to unload an nmethod if it contains otherwise unreachable1817// oops.18181819void nmethod::do_unloading(bool unloading_occurred) {1820// Make sure the oop's ready to receive visitors1821assert(!is_zombie() && !is_unloaded(),1822"should not call follow on zombie or unloaded nmethod");18231824if (is_unloading()) {1825make_unloaded();1826} else {1827guarantee(unload_nmethod_caches(unloading_occurred),1828"Should not need transition stubs");1829}1830}18311832void nmethod::oops_do(OopClosure* f, bool allow_dead) {1833// make sure the oops ready to receive visitors1834assert(allow_dead || is_alive(), "should not call follow on dead nmethod");18351836// Prevent extra code cache walk for platforms that don't have immediate oops.1837if (relocInfo::mustIterateImmediateOopsInCode()) {1838RelocIterator iter(this, oops_reloc_begin());18391840while (iter.next()) {1841if (iter.type() == relocInfo::oop_type ) {1842oop_Relocation* r = iter.oop_reloc();1843// In this loop, we must only follow those oops directly embedded in1844// the code. Other oops (oop_index>0) are seen as part of scopes_oops.1845assert(1 == (r->oop_is_immediate()) +1846(r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),1847"oop must be found in exactly one place");1848if (r->oop_is_immediate() && r->oop_value() != NULL) {1849f->do_oop(r->oop_addr());1850}1851}1852}1853}18541855// Scopes1856// This includes oop constants not inlined in the code stream.1857for (oop* p = oops_begin(); p < oops_end(); p++) {1858if (*p == Universe::non_oop_word()) continue; // skip non-oops1859f->do_oop(p);1860}1861}18621863nmethod* volatile nmethod::_oops_do_mark_nmethods;18641865void nmethod::oops_do_log_change(const char* state) {1866LogTarget(Trace, gc, nmethod) lt;1867if (lt.is_enabled()) {1868LogStream ls(lt);1869CompileTask::print(&ls, this, state, true /* short_form */);1870}1871}18721873bool nmethod::oops_do_try_claim() {1874if (oops_do_try_claim_weak_request()) {1875nmethod* result = oops_do_try_add_to_list_as_weak_done();1876assert(result == NULL, "adding to global list as weak done must always succeed.");1877return true;1878}1879return false;1880}18811882bool nmethod::oops_do_try_claim_weak_request() {1883assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");18841885if ((_oops_do_mark_link == NULL) &&1886(Atomic::replace_if_null(&_oops_do_mark_link, mark_link(this, claim_weak_request_tag)))) {1887oops_do_log_change("oops_do, mark weak request");1888return true;1889}1890return false;1891}18921893void nmethod::oops_do_set_strong_done(nmethod* old_head) {1894_oops_do_mark_link = mark_link(old_head, claim_strong_done_tag);1895}18961897nmethod::oops_do_mark_link* nmethod::oops_do_try_claim_strong_done() {1898assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");18991900oops_do_mark_link* old_next = Atomic::cmpxchg(&_oops_do_mark_link, mark_link(NULL, claim_weak_request_tag), mark_link(this, claim_strong_done_tag));1901if (old_next == NULL) {1902oops_do_log_change("oops_do, mark strong done");1903}1904return old_next;1905}19061907nmethod::oops_do_mark_link* nmethod::oops_do_try_add_strong_request(nmethod::oops_do_mark_link* next) {1908assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");1909assert(next == mark_link(this, claim_weak_request_tag), "Should be claimed as weak");19101911oops_do_mark_link* old_next = Atomic::cmpxchg(&_oops_do_mark_link, next, mark_link(this, claim_strong_request_tag));1912if (old_next == next) {1913oops_do_log_change("oops_do, mark strong request");1914}1915return old_next;1916}19171918bool nmethod::oops_do_try_claim_weak_done_as_strong_done(nmethod::oops_do_mark_link* next) {1919assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");1920assert(extract_state(next) == claim_weak_done_tag, "Should be claimed as weak done");19211922oops_do_mark_link* old_next = Atomic::cmpxchg(&_oops_do_mark_link, next, mark_link(extract_nmethod(next), claim_strong_done_tag));1923if (old_next == next) {1924oops_do_log_change("oops_do, mark weak done -> mark strong done");1925return true;1926}1927return false;1928}19291930nmethod* nmethod::oops_do_try_add_to_list_as_weak_done() {1931assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");19321933assert(extract_state(_oops_do_mark_link) == claim_weak_request_tag ||1934extract_state(_oops_do_mark_link) == claim_strong_request_tag,1935"must be but is nmethod " PTR_FORMAT " %u", p2i(extract_nmethod(_oops_do_mark_link)), extract_state(_oops_do_mark_link));19361937nmethod* old_head = Atomic::xchg(&_oops_do_mark_nmethods, this);1938// Self-loop if needed.1939if (old_head == NULL) {1940old_head = this;1941}1942// Try to install end of list and weak done tag.1943if (Atomic::cmpxchg(&_oops_do_mark_link, mark_link(this, claim_weak_request_tag), mark_link(old_head, claim_weak_done_tag)) == mark_link(this, claim_weak_request_tag)) {1944oops_do_log_change("oops_do, mark weak done");1945return NULL;1946} else {1947return old_head;1948}1949}19501951void nmethod::oops_do_add_to_list_as_strong_done() {1952assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");19531954nmethod* old_head = Atomic::xchg(&_oops_do_mark_nmethods, this);1955// Self-loop if needed.1956if (old_head == NULL) {1957old_head = this;1958}1959assert(_oops_do_mark_link == mark_link(this, claim_strong_done_tag), "must be but is nmethod " PTR_FORMAT " state %u",1960p2i(extract_nmethod(_oops_do_mark_link)), extract_state(_oops_do_mark_link));19611962oops_do_set_strong_done(old_head);1963}19641965void nmethod::oops_do_process_weak(OopsDoProcessor* p) {1966if (!oops_do_try_claim_weak_request()) {1967// Failed to claim for weak processing.1968oops_do_log_change("oops_do, mark weak request fail");1969return;1970}19711972p->do_regular_processing(this);19731974nmethod* old_head = oops_do_try_add_to_list_as_weak_done();1975if (old_head == NULL) {1976return;1977}1978oops_do_log_change("oops_do, mark weak done fail");1979// Adding to global list failed, another thread added a strong request.1980assert(extract_state(_oops_do_mark_link) == claim_strong_request_tag,1981"must be but is %u", extract_state(_oops_do_mark_link));19821983oops_do_log_change("oops_do, mark weak request -> mark strong done");19841985oops_do_set_strong_done(old_head);1986// Do missing strong processing.1987p->do_remaining_strong_processing(this);1988}19891990void nmethod::oops_do_process_strong(OopsDoProcessor* p) {1991oops_do_mark_link* next_raw = oops_do_try_claim_strong_done();1992if (next_raw == NULL) {1993p->do_regular_processing(this);1994oops_do_add_to_list_as_strong_done();1995return;1996}1997// Claim failed. Figure out why and handle it.1998if (oops_do_has_weak_request(next_raw)) {1999oops_do_mark_link* old = next_raw;2000// Claim failed because being weak processed (state == "weak request").2001// Try to request deferred strong processing.2002next_raw = oops_do_try_add_strong_request(old);2003if (next_raw == old) {2004// Successfully requested deferred strong processing.2005return;2006}2007// Failed because of a concurrent transition. No longer in "weak request" state.2008}2009if (oops_do_has_any_strong_state(next_raw)) {2010// Already claimed for strong processing or requested for such.2011return;2012}2013if (oops_do_try_claim_weak_done_as_strong_done(next_raw)) {2014// Successfully claimed "weak done" as "strong done". Do the missing marking.2015p->do_remaining_strong_processing(this);2016return;2017}2018// Claim failed, some other thread got it.2019}20202021void nmethod::oops_do_marking_prologue() {2022assert_at_safepoint();20232024log_trace(gc, nmethod)("oops_do_marking_prologue");2025assert(_oops_do_mark_nmethods == NULL, "must be empty");2026}20272028void nmethod::oops_do_marking_epilogue() {2029assert_at_safepoint();20302031nmethod* next = _oops_do_mark_nmethods;2032_oops_do_mark_nmethods = NULL;2033if (next != NULL) {2034nmethod* cur;2035do {2036cur = next;2037next = extract_nmethod(cur->_oops_do_mark_link);2038cur->_oops_do_mark_link = NULL;2039DEBUG_ONLY(cur->verify_oop_relocations());20402041LogTarget(Trace, gc, nmethod) lt;2042if (lt.is_enabled()) {2043LogStream ls(lt);2044CompileTask::print(&ls, cur, "oops_do, unmark", /*short_form:*/ true);2045}2046// End if self-loop has been detected.2047} while (cur != next);2048}2049log_trace(gc, nmethod)("oops_do_marking_epilogue");2050}20512052inline bool includes(void* p, void* from, void* to) {2053return from <= p && p < to;2054}205520562057void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) {2058assert(count >= 2, "must be sentinel values, at least");20592060#ifdef ASSERT2061// must be sorted and unique; we do a binary search in find_pc_desc()2062int prev_offset = pcs[0].pc_offset();2063assert(prev_offset == PcDesc::lower_offset_limit,2064"must start with a sentinel");2065for (int i = 1; i < count; i++) {2066int this_offset = pcs[i].pc_offset();2067assert(this_offset > prev_offset, "offsets must be sorted");2068prev_offset = this_offset;2069}2070assert(prev_offset == PcDesc::upper_offset_limit,2071"must end with a sentinel");2072#endif //ASSERT20732074// Search for MethodHandle invokes and tag the nmethod.2075for (int i = 0; i < count; i++) {2076if (pcs[i].is_method_handle_invoke()) {2077set_has_method_handle_invokes(true);2078break;2079}2080}2081assert(has_method_handle_invokes() == (_deopt_mh_handler_begin != NULL), "must have deopt mh handler");20822083int size = count * sizeof(PcDesc);2084assert(scopes_pcs_size() >= size, "oob");2085memcpy(scopes_pcs_begin(), pcs, size);20862087// Adjust the final sentinel downward.2088PcDesc* last_pc = &scopes_pcs_begin()[count-1];2089assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity");2090last_pc->set_pc_offset(content_size() + 1);2091for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) {2092// Fill any rounding gaps with copies of the last record.2093last_pc[1] = last_pc[0];2094}2095// The following assert could fail if sizeof(PcDesc) is not2096// an integral multiple of oopSize (the rounding term).2097// If it fails, change the logic to always allocate a multiple2098// of sizeof(PcDesc), and fill unused words with copies of *last_pc.2099assert(last_pc + 1 == scopes_pcs_end(), "must match exactly");2100}21012102void nmethod::copy_scopes_data(u_char* buffer, int size) {2103assert(scopes_data_size() >= size, "oob");2104memcpy(scopes_data_begin(), buffer, size);2105}21062107#ifdef ASSERT2108static PcDesc* linear_search(const PcDescSearch& search, int pc_offset, bool approximate) {2109PcDesc* lower = search.scopes_pcs_begin();2110PcDesc* upper = search.scopes_pcs_end();2111lower += 1; // exclude initial sentinel2112PcDesc* res = NULL;2113for (PcDesc* p = lower; p < upper; p++) {2114NOT_PRODUCT(--pc_nmethod_stats.pc_desc_tests); // don't count this call to match_desc2115if (match_desc(p, pc_offset, approximate)) {2116if (res == NULL)2117res = p;2118else2119res = (PcDesc*) badAddress;2120}2121}2122return res;2123}2124#endif212521262127// Finds a PcDesc with real-pc equal to "pc"2128PcDesc* PcDescContainer::find_pc_desc_internal(address pc, bool approximate, const PcDescSearch& search) {2129address base_address = search.code_begin();2130if ((pc < base_address) ||2131(pc - base_address) >= (ptrdiff_t) PcDesc::upper_offset_limit) {2132return NULL; // PC is wildly out of range2133}2134int pc_offset = (int) (pc - base_address);21352136// Check the PcDesc cache if it contains the desired PcDesc2137// (This as an almost 100% hit rate.)2138PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate);2139if (res != NULL) {2140assert(res == linear_search(search, pc_offset, approximate), "cache ok");2141return res;2142}21432144// Fallback algorithm: quasi-linear search for the PcDesc2145// Find the last pc_offset less than the given offset.2146// The successor must be the required match, if there is a match at all.2147// (Use a fixed radix to avoid expensive affine pointer arithmetic.)2148PcDesc* lower = search.scopes_pcs_begin();2149PcDesc* upper = search.scopes_pcs_end();2150upper -= 1; // exclude final sentinel2151if (lower >= upper) return NULL; // native method; no PcDescs at all21522153#define assert_LU_OK \2154/* invariant on lower..upper during the following search: */ \2155assert(lower->pc_offset() < pc_offset, "sanity"); \2156assert(upper->pc_offset() >= pc_offset, "sanity")2157assert_LU_OK;21582159// Use the last successful return as a split point.2160PcDesc* mid = _pc_desc_cache.last_pc_desc();2161NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);2162if (mid->pc_offset() < pc_offset) {2163lower = mid;2164} else {2165upper = mid;2166}21672168// Take giant steps at first (4096, then 256, then 16, then 1)2169const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ debug_only(-1);2170const int RADIX = (1 << LOG2_RADIX);2171for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) {2172while ((mid = lower + step) < upper) {2173assert_LU_OK;2174NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);2175if (mid->pc_offset() < pc_offset) {2176lower = mid;2177} else {2178upper = mid;2179break;2180}2181}2182assert_LU_OK;2183}21842185// Sneak up on the value with a linear search of length ~16.2186while (true) {2187assert_LU_OK;2188mid = lower + 1;2189NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);2190if (mid->pc_offset() < pc_offset) {2191lower = mid;2192} else {2193upper = mid;2194break;2195}2196}2197#undef assert_LU_OK21982199if (match_desc(upper, pc_offset, approximate)) {2200assert(upper == linear_search(search, pc_offset, approximate), "search ok");2201_pc_desc_cache.add_pc_desc(upper);2202return upper;2203} else {2204assert(NULL == linear_search(search, pc_offset, approximate), "search ok");2205return NULL;2206}2207}220822092210void nmethod::check_all_dependencies(DepChange& changes) {2211// Checked dependencies are allocated into this ResourceMark2212ResourceMark rm;22132214// Turn off dependency tracing while actually testing dependencies.2215NOT_PRODUCT( FlagSetting fs(TraceDependencies, false) );22162217typedef ResourceHashtable<DependencySignature, int, &DependencySignature::hash,2218&DependencySignature::equals, 11027> DepTable;22192220DepTable* table = new DepTable();22212222// Iterate over live nmethods and check dependencies of all nmethods that are not2223// marked for deoptimization. A particular dependency is only checked once.2224NMethodIterator iter(NMethodIterator::only_alive_and_not_unloading);2225while(iter.next()) {2226nmethod* nm = iter.method();2227// Only notify for live nmethods2228if (!nm->is_marked_for_deoptimization()) {2229for (Dependencies::DepStream deps(nm); deps.next(); ) {2230// Construct abstraction of a dependency.2231DependencySignature* current_sig = new DependencySignature(deps);22322233// Determine if dependency is already checked. table->put(...) returns2234// 'true' if the dependency is added (i.e., was not in the hashtable).2235if (table->put(*current_sig, 1)) {2236if (deps.check_dependency() != NULL) {2237// Dependency checking failed. Print out information about the failed2238// dependency and finally fail with an assert. We can fail here, since2239// dependency checking is never done in a product build.2240tty->print_cr("Failed dependency:");2241changes.print();2242nm->print();2243nm->print_dependencies();2244assert(false, "Should have been marked for deoptimization");2245}2246}2247}2248}2249}2250}22512252bool nmethod::check_dependency_on(DepChange& changes) {2253// What has happened:2254// 1) a new class dependee has been added2255// 2) dependee and all its super classes have been marked2256bool found_check = false; // set true if we are upset2257for (Dependencies::DepStream deps(this); deps.next(); ) {2258// Evaluate only relevant dependencies.2259if (deps.spot_check_dependency_at(changes) != NULL) {2260found_check = true;2261NOT_DEBUG(break);2262}2263}2264return found_check;2265}22662267// Called from mark_for_deoptimization, when dependee is invalidated.2268bool nmethod::is_dependent_on_method(Method* dependee) {2269for (Dependencies::DepStream deps(this); deps.next(); ) {2270if (deps.type() != Dependencies::evol_method)2271continue;2272Method* method = deps.method_argument(0);2273if (method == dependee) return true;2274}2275return false;2276}227722782279bool nmethod::is_patchable_at(address instr_addr) {2280assert(insts_contains(instr_addr), "wrong nmethod used");2281if (is_zombie()) {2282// a zombie may never be patched2283return false;2284}2285return true;2286}228722882289void nmethod_init() {2290// make sure you didn't forget to adjust the filler fields2291assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word");2292}229322942295//-------------------------------------------------------------------------------------------229622972298// QQQ might we make this work from a frame??2299nmethodLocker::nmethodLocker(address pc) {2300CodeBlob* cb = CodeCache::find_blob(pc);2301guarantee(cb != NULL && cb->is_compiled(), "bad pc for a nmethod found");2302_nm = cb->as_compiled_method();2303lock_nmethod(_nm);2304}23052306// Only JvmtiDeferredEvent::compiled_method_unload_event()2307// should pass zombie_ok == true.2308void nmethodLocker::lock_nmethod(CompiledMethod* cm, bool zombie_ok) {2309if (cm == NULL) return;2310nmethod* nm = cm->as_nmethod();2311Atomic::inc(&nm->_lock_count);2312assert(zombie_ok || !nm->is_zombie(), "cannot lock a zombie method: %p", nm);2313}23142315void nmethodLocker::unlock_nmethod(CompiledMethod* cm) {2316if (cm == NULL) return;2317nmethod* nm = cm->as_nmethod();2318Atomic::dec(&nm->_lock_count);2319assert(nm->_lock_count >= 0, "unmatched nmethod lock/unlock");2320}232123222323// -----------------------------------------------------------------------------2324// Verification23252326class VerifyOopsClosure: public OopClosure {2327nmethod* _nm;2328bool _ok;2329public:2330VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { }2331bool ok() { return _ok; }2332virtual void do_oop(oop* p) {2333if (oopDesc::is_oop_or_null(*p)) return;2334// Print diagnostic information before calling print_nmethod().2335// Assertions therein might prevent call from returning.2336tty->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)",2337p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm));2338if (_ok) {2339_nm->print_nmethod(true);2340_ok = false;2341}2342}2343virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }2344};23452346class VerifyMetadataClosure: public MetadataClosure {2347public:2348void do_metadata(Metadata* md) {2349if (md->is_method()) {2350Method* method = (Method*)md;2351assert(!method->is_old(), "Should not be installing old methods");2352}2353}2354};235523562357void nmethod::verify() {23582359// Hmm. OSR methods can be deopted but not marked as zombie or not_entrant2360// seems odd.23612362if (is_zombie() || is_not_entrant() || is_unloaded())2363return;23642365// Make sure all the entry points are correctly aligned for patching.2366NativeJump::check_verified_entry_alignment(entry_point(), verified_entry_point());23672368// assert(oopDesc::is_oop(method()), "must be valid");23692370ResourceMark rm;23712372if (!CodeCache::contains(this)) {2373fatal("nmethod at " INTPTR_FORMAT " not in zone", p2i(this));2374}23752376if(is_native_method() )2377return;23782379nmethod* nm = CodeCache::find_nmethod(verified_entry_point());2380if (nm != this) {2381fatal("findNMethod did not find this nmethod (" INTPTR_FORMAT ")", p2i(this));2382}23832384for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {2385if (! p->verify(this)) {2386tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", p2i(this));2387}2388}23892390#ifdef ASSERT2391#if INCLUDE_JVMCI2392{2393// Verify that implicit exceptions that deoptimize have a PcDesc and OopMap2394ImmutableOopMapSet* oms = oop_maps();2395ImplicitExceptionTable implicit_table(this);2396for (uint i = 0; i < implicit_table.len(); i++) {2397int exec_offset = (int) implicit_table.get_exec_offset(i);2398if (implicit_table.get_exec_offset(i) == implicit_table.get_cont_offset(i)) {2399assert(pc_desc_at(code_begin() + exec_offset) != NULL, "missing PcDesc");2400bool found = false;2401for (int i = 0, imax = oms->count(); i < imax; i++) {2402if (oms->pair_at(i)->pc_offset() == exec_offset) {2403found = true;2404break;2405}2406}2407assert(found, "missing oopmap");2408}2409}2410}2411#endif2412#endif24132414VerifyOopsClosure voc(this);2415oops_do(&voc);2416assert(voc.ok(), "embedded oops must be OK");2417Universe::heap()->verify_nmethod(this);24182419assert(_oops_do_mark_link == NULL, "_oops_do_mark_link for %s should be NULL but is " PTR_FORMAT,2420nm->method()->external_name(), p2i(_oops_do_mark_link));2421verify_scopes();24222423CompiledICLocker nm_verify(this);2424VerifyMetadataClosure vmc;2425metadata_do(&vmc);2426}242724282429void nmethod::verify_interrupt_point(address call_site) {24302431// Verify IC only when nmethod installation is finished.2432if (!is_not_installed()) {2433if (CompiledICLocker::is_safe(this)) {2434CompiledIC_at(this, call_site);2435} else {2436CompiledICLocker ml_verify(this);2437CompiledIC_at(this, call_site);2438}2439}24402441HandleMark hm(Thread::current());24422443PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address());2444assert(pd != NULL, "PcDesc must exist");2445for (ScopeDesc* sd = new ScopeDesc(this, pd);2446!sd->is_top(); sd = sd->sender()) {2447sd->verify();2448}2449}24502451void nmethod::verify_scopes() {2452if( !method() ) return; // Runtime stubs have no scope2453if (method()->is_native()) return; // Ignore stub methods.2454// iterate through all interrupt point2455// and verify the debug information is valid.2456RelocIterator iter((nmethod*)this);2457while (iter.next()) {2458address stub = NULL;2459switch (iter.type()) {2460case relocInfo::virtual_call_type:2461verify_interrupt_point(iter.addr());2462break;2463case relocInfo::opt_virtual_call_type:2464stub = iter.opt_virtual_call_reloc()->static_stub();2465verify_interrupt_point(iter.addr());2466break;2467case relocInfo::static_call_type:2468stub = iter.static_call_reloc()->static_stub();2469//verify_interrupt_point(iter.addr());2470break;2471case relocInfo::runtime_call_type:2472case relocInfo::runtime_call_w_cp_type: {2473address destination = iter.reloc()->value();2474// Right now there is no way to find out which entries support2475// an interrupt point. It would be nice if we had this2476// information in a table.2477break;2478}2479default:2480break;2481}2482assert(stub == NULL || stub_contains(stub), "static call stub outside stub section");2483}2484}248524862487// -----------------------------------------------------------------------------2488// Printing operations24892490void nmethod::print() const {2491ttyLocker ttyl; // keep the following output all in one block2492print(tty);2493}24942495void nmethod::print(outputStream* st) const {2496ResourceMark rm;24972498st->print("Compiled method ");24992500if (is_compiled_by_c1()) {2501st->print("(c1) ");2502} else if (is_compiled_by_c2()) {2503st->print("(c2) ");2504} else if (is_compiled_by_jvmci()) {2505st->print("(JVMCI) ");2506} else {2507st->print("(n/a) ");2508}25092510print_on(tty, NULL);25112512if (WizardMode) {2513st->print("((nmethod*) " INTPTR_FORMAT ") ", p2i(this));2514st->print(" for method " INTPTR_FORMAT , p2i(method()));2515st->print(" { ");2516st->print_cr("%s ", state());2517st->print_cr("}:");2518}2519if (size () > 0) st->print_cr(" total in heap [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2520p2i(this),2521p2i(this) + size(),2522size());2523if (relocation_size () > 0) st->print_cr(" relocation [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2524p2i(relocation_begin()),2525p2i(relocation_end()),2526relocation_size());2527if (consts_size () > 0) st->print_cr(" constants [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2528p2i(consts_begin()),2529p2i(consts_end()),2530consts_size());2531if (insts_size () > 0) st->print_cr(" main code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2532p2i(insts_begin()),2533p2i(insts_end()),2534insts_size());2535if (stub_size () > 0) st->print_cr(" stub code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2536p2i(stub_begin()),2537p2i(stub_end()),2538stub_size());2539if (oops_size () > 0) st->print_cr(" oops [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2540p2i(oops_begin()),2541p2i(oops_end()),2542oops_size());2543if (metadata_size () > 0) st->print_cr(" metadata [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2544p2i(metadata_begin()),2545p2i(metadata_end()),2546metadata_size());2547if (scopes_data_size () > 0) st->print_cr(" scopes data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2548p2i(scopes_data_begin()),2549p2i(scopes_data_end()),2550scopes_data_size());2551if (scopes_pcs_size () > 0) st->print_cr(" scopes pcs [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2552p2i(scopes_pcs_begin()),2553p2i(scopes_pcs_end()),2554scopes_pcs_size());2555if (dependencies_size () > 0) st->print_cr(" dependencies [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2556p2i(dependencies_begin()),2557p2i(dependencies_end()),2558dependencies_size());2559if (handler_table_size() > 0) st->print_cr(" handler table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2560p2i(handler_table_begin()),2561p2i(handler_table_end()),2562handler_table_size());2563if (nul_chk_table_size() > 0) st->print_cr(" nul chk table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2564p2i(nul_chk_table_begin()),2565p2i(nul_chk_table_end()),2566nul_chk_table_size());2567#if INCLUDE_JVMCI2568if (speculations_size () > 0) st->print_cr(" speculations [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2569p2i(speculations_begin()),2570p2i(speculations_end()),2571speculations_size());2572if (jvmci_data_size () > 0) st->print_cr(" JVMCI data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2573p2i(jvmci_data_begin()),2574p2i(jvmci_data_end()),2575jvmci_data_size());2576#endif2577}25782579void nmethod::print_code() {2580ResourceMark m;2581ttyLocker ttyl;2582// Call the specialized decode method of this class.2583decode(tty);2584}25852586#ifndef PRODUCT // called InstanceKlass methods are available only then. Declared as PRODUCT_RETURN25872588void nmethod::print_dependencies() {2589ResourceMark rm;2590ttyLocker ttyl; // keep the following output all in one block2591tty->print_cr("Dependencies:");2592for (Dependencies::DepStream deps(this); deps.next(); ) {2593deps.print_dependency();2594Klass* ctxk = deps.context_type();2595if (ctxk != NULL) {2596if (ctxk->is_instance_klass() && InstanceKlass::cast(ctxk)->is_dependent_nmethod(this)) {2597tty->print_cr(" [nmethod<=klass]%s", ctxk->external_name());2598}2599}2600deps.log_dependency(); // put it into the xml log also2601}2602}2603#endif26042605#if defined(SUPPORT_DATA_STRUCTS)26062607// Print the oops from the underlying CodeBlob.2608void nmethod::print_oops(outputStream* st) {2609ResourceMark m;2610st->print("Oops:");2611if (oops_begin() < oops_end()) {2612st->cr();2613for (oop* p = oops_begin(); p < oops_end(); p++) {2614Disassembler::print_location((unsigned char*)p, (unsigned char*)oops_begin(), (unsigned char*)oops_end(), st, true, false);2615st->print(PTR_FORMAT " ", *((uintptr_t*)p));2616if (Universe::contains_non_oop_word(p)) {2617st->print_cr("NON_OOP");2618continue; // skip non-oops2619}2620if (*p == NULL) {2621st->print_cr("NULL-oop");2622continue; // skip non-oops2623}2624(*p)->print_value_on(st);2625st->cr();2626}2627} else {2628st->print_cr(" <list empty>");2629}2630}26312632// Print metadata pool.2633void nmethod::print_metadata(outputStream* st) {2634ResourceMark m;2635st->print("Metadata:");2636if (metadata_begin() < metadata_end()) {2637st->cr();2638for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {2639Disassembler::print_location((unsigned char*)p, (unsigned char*)metadata_begin(), (unsigned char*)metadata_end(), st, true, false);2640st->print(PTR_FORMAT " ", *((uintptr_t*)p));2641if (*p && *p != Universe::non_oop_word()) {2642(*p)->print_value_on(st);2643}2644st->cr();2645}2646} else {2647st->print_cr(" <list empty>");2648}2649}26502651#ifndef PRODUCT // ScopeDesc::print_on() is available only then. Declared as PRODUCT_RETURN2652void nmethod::print_scopes_on(outputStream* st) {2653// Find the first pc desc for all scopes in the code and print it.2654ResourceMark rm;2655st->print("scopes:");2656if (scopes_pcs_begin() < scopes_pcs_end()) {2657st->cr();2658for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {2659if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null)2660continue;26612662ScopeDesc* sd = scope_desc_at(p->real_pc(this));2663while (sd != NULL) {2664sd->print_on(st, p); // print output ends with a newline2665sd = sd->sender();2666}2667}2668} else {2669st->print_cr(" <list empty>");2670}2671}2672#endif26732674#ifndef PRODUCT // RelocIterator does support printing only then.2675void nmethod::print_relocations() {2676ResourceMark m; // in case methods get printed via the debugger2677tty->print_cr("relocations:");2678RelocIterator iter(this);2679iter.print();2680}2681#endif26822683void nmethod::print_pcs_on(outputStream* st) {2684ResourceMark m; // in case methods get printed via debugger2685st->print("pc-bytecode offsets:");2686if (scopes_pcs_begin() < scopes_pcs_end()) {2687st->cr();2688for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {2689p->print_on(st, this); // print output ends with a newline2690}2691} else {2692st->print_cr(" <list empty>");2693}2694}26952696void nmethod::print_native_invokers() {2697ResourceMark m; // in case methods get printed via debugger2698tty->print_cr("Native invokers:");2699for (RuntimeStub** itt = native_invokers_begin(); itt < native_invokers_end(); itt++) {2700(*itt)->print_on(tty);2701}2702}27032704void nmethod::print_handler_table() {2705ExceptionHandlerTable(this).print(code_begin());2706}27072708void nmethod::print_nul_chk_table() {2709ImplicitExceptionTable(this).print(code_begin());2710}27112712void nmethod::print_recorded_oop(int log_n, int i) {2713void* value;27142715if (i == 0) {2716value = NULL;2717} else {2718// Be careful around non-oop words. Don't create an oop2719// with that value, or it will assert in verification code.2720if (Universe::contains_non_oop_word(oop_addr_at(i))) {2721value = Universe::non_oop_word();2722} else {2723value = oop_at(i);2724}2725}27262727tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(value));27282729if (value == Universe::non_oop_word()) {2730tty->print("non-oop word");2731} else {2732if (value == 0) {2733tty->print("NULL-oop");2734} else {2735oop_at(i)->print_value_on(tty);2736}2737}27382739tty->cr();2740}27412742void nmethod::print_recorded_oops() {2743const int n = oops_count();2744const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6;2745tty->print("Recorded oops:");2746if (n > 0) {2747tty->cr();2748for (int i = 0; i < n; i++) {2749print_recorded_oop(log_n, i);2750}2751} else {2752tty->print_cr(" <list empty>");2753}2754}27552756void nmethod::print_recorded_metadata() {2757const int n = metadata_count();2758const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6;2759tty->print("Recorded metadata:");2760if (n > 0) {2761tty->cr();2762for (int i = 0; i < n; i++) {2763Metadata* m = metadata_at(i);2764tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(m));2765if (m == (Metadata*)Universe::non_oop_word()) {2766tty->print("non-metadata word");2767} else if (m == NULL) {2768tty->print("NULL-oop");2769} else {2770Metadata::print_value_on_maybe_null(tty, m);2771}2772tty->cr();2773}2774} else {2775tty->print_cr(" <list empty>");2776}2777}2778#endif27792780#if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)27812782void nmethod::print_constant_pool(outputStream* st) {2783//-----------------------------------2784//---< Print the constant pool >---2785//-----------------------------------2786int consts_size = this->consts_size();2787if ( consts_size > 0 ) {2788unsigned char* cstart = this->consts_begin();2789unsigned char* cp = cstart;2790unsigned char* cend = cp + consts_size;2791unsigned int bytes_per_line = 4;2792unsigned int CP_alignment = 8;2793unsigned int n;27942795st->cr();27962797//---< print CP header to make clear what's printed >---2798if( ((uintptr_t)cp&(CP_alignment-1)) == 0 ) {2799n = bytes_per_line;2800st->print_cr("[Constant Pool]");2801Disassembler::print_location(cp, cstart, cend, st, true, true);2802Disassembler::print_hexdata(cp, n, st, true);2803st->cr();2804} else {2805n = (uintptr_t)cp&(bytes_per_line-1);2806st->print_cr("[Constant Pool (unaligned)]");2807}28082809//---< print CP contents, bytes_per_line at a time >---2810while (cp < cend) {2811Disassembler::print_location(cp, cstart, cend, st, true, false);2812Disassembler::print_hexdata(cp, n, st, false);2813cp += n;2814n = bytes_per_line;2815st->cr();2816}28172818//---< Show potential alignment gap between constant pool and code >---2819cend = code_begin();2820if( cp < cend ) {2821n = 4;2822st->print_cr("[Code entry alignment]");2823while (cp < cend) {2824Disassembler::print_location(cp, cstart, cend, st, false, false);2825cp += n;2826st->cr();2827}2828}2829} else {2830st->print_cr("[Constant Pool (empty)]");2831}2832st->cr();2833}28342835#endif28362837// Disassemble this nmethod.2838// Print additional debug information, if requested. This could be code2839// comments, block comments, profiling counters, etc.2840// The undisassembled format is useful no disassembler library is available.2841// The resulting hex dump (with markers) can be disassembled later, or on2842// another system, when/where a disassembler library is available.2843void nmethod::decode2(outputStream* ost) const {28442845// Called from frame::back_trace_with_decode without ResourceMark.2846ResourceMark rm;28472848// Make sure we have a valid stream to print on.2849outputStream* st = ost ? ost : tty;28502851#if defined(SUPPORT_ABSTRACT_ASSEMBLY) && ! defined(SUPPORT_ASSEMBLY)2852const bool use_compressed_format = true;2853const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() ||2854AbstractDisassembler::show_block_comment());2855#else2856const bool use_compressed_format = Disassembler::is_abstract();2857const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() ||2858AbstractDisassembler::show_block_comment());2859#endif28602861st->cr();2862this->print(st);2863st->cr();28642865#if defined(SUPPORT_ASSEMBLY)2866//----------------------------------2867//---< Print real disassembly >---2868//----------------------------------2869if (! use_compressed_format) {2870Disassembler::decode(const_cast<nmethod*>(this), st);2871return;2872}2873#endif28742875#if defined(SUPPORT_ABSTRACT_ASSEMBLY)28762877// Compressed undisassembled disassembly format.2878// The following stati are defined/supported:2879// = 0 - currently at bol() position, nothing printed yet on current line.2880// = 1 - currently at position after print_location().2881// > 1 - in the midst of printing instruction stream bytes.2882int compressed_format_idx = 0;2883int code_comment_column = 0;2884const int instr_maxlen = Assembler::instr_maxlen();2885const uint tabspacing = 8;2886unsigned char* start = this->code_begin();2887unsigned char* p = this->code_begin();2888unsigned char* end = this->code_end();2889unsigned char* pss = p; // start of a code section (used for offsets)28902891if ((start == NULL) || (end == NULL)) {2892st->print_cr("PrintAssembly not possible due to uninitialized section pointers");2893return;2894}2895#endif28962897#if defined(SUPPORT_ABSTRACT_ASSEMBLY)2898//---< plain abstract disassembly, no comments or anything, just section headers >---2899if (use_compressed_format && ! compressed_with_comments) {2900const_cast<nmethod*>(this)->print_constant_pool(st);29012902//---< Open the output (Marker for post-mortem disassembler) >---2903st->print_cr("[MachCode]");2904const char* header = NULL;2905address p0 = p;2906while (p < end) {2907address pp = p;2908while ((p < end) && (header == NULL)) {2909header = nmethod_section_label(p);2910pp = p;2911p += Assembler::instr_len(p);2912}2913if (pp > p0) {2914AbstractDisassembler::decode_range_abstract(p0, pp, start, end, st, Assembler::instr_maxlen());2915p0 = pp;2916p = pp;2917header = NULL;2918} else if (header != NULL) {2919st->bol();2920st->print_cr("%s", header);2921header = NULL;2922}2923}2924//---< Close the output (Marker for post-mortem disassembler) >---2925st->bol();2926st->print_cr("[/MachCode]");2927return;2928}2929#endif29302931#if defined(SUPPORT_ABSTRACT_ASSEMBLY)2932//---< abstract disassembly with comments and section headers merged in >---2933if (compressed_with_comments) {2934const_cast<nmethod*>(this)->print_constant_pool(st);29352936//---< Open the output (Marker for post-mortem disassembler) >---2937st->print_cr("[MachCode]");2938while ((p < end) && (p != NULL)) {2939const int instruction_size_in_bytes = Assembler::instr_len(p);29402941//---< Block comments for nmethod. Interrupts instruction stream, if any. >---2942// Outputs a bol() before and a cr() after, but only if a comment is printed.2943// Prints nmethod_section_label as well.2944if (AbstractDisassembler::show_block_comment()) {2945print_block_comment(st, p);2946if (st->position() == 0) {2947compressed_format_idx = 0;2948}2949}29502951//---< New location information after line break >---2952if (compressed_format_idx == 0) {2953code_comment_column = Disassembler::print_location(p, pss, end, st, false, false);2954compressed_format_idx = 1;2955}29562957//---< Code comment for current instruction. Address range [p..(p+len)) >---2958unsigned char* p_end = p + (ssize_t)instruction_size_in_bytes;2959S390_ONLY(if (p_end > end) p_end = end;) // avoid getting past the end29602961if (AbstractDisassembler::show_comment() && const_cast<nmethod*>(this)->has_code_comment(p, p_end)) {2962//---< interrupt instruction byte stream for code comment >---2963if (compressed_format_idx > 1) {2964st->cr(); // interrupt byte stream2965st->cr(); // add an empty line2966code_comment_column = Disassembler::print_location(p, pss, end, st, false, false);2967}2968const_cast<nmethod*>(this)->print_code_comment_on(st, code_comment_column, p, p_end );2969st->bol();2970compressed_format_idx = 0;2971}29722973//---< New location information after line break >---2974if (compressed_format_idx == 0) {2975code_comment_column = Disassembler::print_location(p, pss, end, st, false, false);2976compressed_format_idx = 1;2977}29782979//---< Nicely align instructions for readability >---2980if (compressed_format_idx > 1) {2981Disassembler::print_delimiter(st);2982}29832984//---< Now, finally, print the actual instruction bytes >---2985unsigned char* p0 = p;2986p = Disassembler::decode_instruction_abstract(p, st, instruction_size_in_bytes, instr_maxlen);2987compressed_format_idx += p - p0;29882989if (Disassembler::start_newline(compressed_format_idx-1)) {2990st->cr();2991compressed_format_idx = 0;2992}2993}2994//---< Close the output (Marker for post-mortem disassembler) >---2995st->bol();2996st->print_cr("[/MachCode]");2997return;2998}2999#endif3000}30013002#if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)30033004const char* nmethod::reloc_string_for(u_char* begin, u_char* end) {3005RelocIterator iter(this, begin, end);3006bool have_one = false;3007while (iter.next()) {3008have_one = true;3009switch (iter.type()) {3010case relocInfo::none: return "no_reloc";3011case relocInfo::oop_type: {3012// Get a non-resizable resource-allocated stringStream.3013// Our callees make use of (nested) ResourceMarks.3014stringStream st(NEW_RESOURCE_ARRAY(char, 1024), 1024);3015oop_Relocation* r = iter.oop_reloc();3016oop obj = r->oop_value();3017st.print("oop(");3018if (obj == NULL) st.print("NULL");3019else obj->print_value_on(&st);3020st.print(")");3021return st.as_string();3022}3023case relocInfo::metadata_type: {3024stringStream st;3025metadata_Relocation* r = iter.metadata_reloc();3026Metadata* obj = r->metadata_value();3027st.print("metadata(");3028if (obj == NULL) st.print("NULL");3029else obj->print_value_on(&st);3030st.print(")");3031return st.as_string();3032}3033case relocInfo::runtime_call_type:3034case relocInfo::runtime_call_w_cp_type: {3035stringStream st;3036st.print("runtime_call");3037CallRelocation* r = (CallRelocation*)iter.reloc();3038address dest = r->destination();3039CodeBlob* cb = CodeCache::find_blob(dest);3040if (cb != NULL) {3041st.print(" %s", cb->name());3042} else {3043ResourceMark rm;3044const int buflen = 1024;3045char* buf = NEW_RESOURCE_ARRAY(char, buflen);3046int offset;3047if (os::dll_address_to_function_name(dest, buf, buflen, &offset)) {3048st.print(" %s", buf);3049if (offset != 0) {3050st.print("+%d", offset);3051}3052}3053}3054return st.as_string();3055}3056case relocInfo::virtual_call_type: {3057stringStream st;3058st.print_raw("virtual_call");3059virtual_call_Relocation* r = iter.virtual_call_reloc();3060Method* m = r->method_value();3061if (m != NULL) {3062assert(m->is_method(), "");3063m->print_short_name(&st);3064}3065return st.as_string();3066}3067case relocInfo::opt_virtual_call_type: {3068stringStream st;3069st.print_raw("optimized virtual_call");3070opt_virtual_call_Relocation* r = iter.opt_virtual_call_reloc();3071Method* m = r->method_value();3072if (m != NULL) {3073assert(m->is_method(), "");3074m->print_short_name(&st);3075}3076return st.as_string();3077}3078case relocInfo::static_call_type: {3079stringStream st;3080st.print_raw("static_call");3081static_call_Relocation* r = iter.static_call_reloc();3082Method* m = r->method_value();3083if (m != NULL) {3084assert(m->is_method(), "");3085m->print_short_name(&st);3086}3087return st.as_string();3088}3089case relocInfo::static_stub_type: return "static_stub";3090case relocInfo::external_word_type: return "external_word";3091case relocInfo::internal_word_type: return "internal_word";3092case relocInfo::section_word_type: return "section_word";3093case relocInfo::poll_type: return "poll";3094case relocInfo::poll_return_type: return "poll_return";3095case relocInfo::trampoline_stub_type: return "trampoline_stub";3096case relocInfo::type_mask: return "type_bit_mask";30973098default:3099break;3100}3101}3102return have_one ? "other" : NULL;3103}31043105// Return a the last scope in (begin..end]3106ScopeDesc* nmethod::scope_desc_in(address begin, address end) {3107PcDesc* p = pc_desc_near(begin+1);3108if (p != NULL && p->real_pc(this) <= end) {3109return new ScopeDesc(this, p);3110}3111return NULL;3112}31133114const char* nmethod::nmethod_section_label(address pos) const {3115const char* label = NULL;3116if (pos == code_begin()) label = "[Instructions begin]";3117if (pos == entry_point()) label = "[Entry Point]";3118if (pos == verified_entry_point()) label = "[Verified Entry Point]";3119if (has_method_handle_invokes() && (pos == deopt_mh_handler_begin())) label = "[Deopt MH Handler Code]";3120if (pos == consts_begin() && pos != insts_begin()) label = "[Constants]";3121// Check stub_code before checking exception_handler or deopt_handler.3122if (pos == this->stub_begin()) label = "[Stub Code]";3123if (JVMCI_ONLY(_exception_offset >= 0 &&) pos == exception_begin()) label = "[Exception Handler]";3124if (JVMCI_ONLY(_deopt_handler_begin != NULL &&) pos == deopt_handler_begin()) label = "[Deopt Handler Code]";3125return label;3126}31273128void nmethod::print_nmethod_labels(outputStream* stream, address block_begin, bool print_section_labels) const {3129if (print_section_labels) {3130const char* label = nmethod_section_label(block_begin);3131if (label != NULL) {3132stream->bol();3133stream->print_cr("%s", label);3134}3135}31363137if (block_begin == entry_point()) {3138Method* m = method();3139if (m != NULL) {3140stream->print(" # ");3141m->print_value_on(stream);3142stream->cr();3143}3144if (m != NULL && !is_osr_method()) {3145ResourceMark rm;3146int sizeargs = m->size_of_parameters();3147BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs);3148VMRegPair* regs = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs);3149{3150int sig_index = 0;3151if (!m->is_static())3152sig_bt[sig_index++] = T_OBJECT; // 'this'3153for (SignatureStream ss(m->signature()); !ss.at_return_type(); ss.next()) {3154BasicType t = ss.type();3155sig_bt[sig_index++] = t;3156if (type2size[t] == 2) {3157sig_bt[sig_index++] = T_VOID;3158} else {3159assert(type2size[t] == 1, "size is 1 or 2");3160}3161}3162assert(sig_index == sizeargs, "");3163}3164const char* spname = "sp"; // make arch-specific?3165intptr_t out_preserve = SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs);3166int stack_slot_offset = this->frame_size() * wordSize;3167int tab1 = 14, tab2 = 24;3168int sig_index = 0;3169int arg_index = (m->is_static() ? 0 : -1);3170bool did_old_sp = false;3171for (SignatureStream ss(m->signature()); !ss.at_return_type(); ) {3172bool at_this = (arg_index == -1);3173bool at_old_sp = false;3174BasicType t = (at_this ? T_OBJECT : ss.type());3175assert(t == sig_bt[sig_index], "sigs in sync");3176if (at_this)3177stream->print(" # this: ");3178else3179stream->print(" # parm%d: ", arg_index);3180stream->move_to(tab1);3181VMReg fst = regs[sig_index].first();3182VMReg snd = regs[sig_index].second();3183if (fst->is_reg()) {3184stream->print("%s", fst->name());3185if (snd->is_valid()) {3186stream->print(":%s", snd->name());3187}3188} else if (fst->is_stack()) {3189int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset;3190if (offset == stack_slot_offset) at_old_sp = true;3191stream->print("[%s+0x%x]", spname, offset);3192} else {3193stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd);3194}3195stream->print(" ");3196stream->move_to(tab2);3197stream->print("= ");3198if (at_this) {3199m->method_holder()->print_value_on(stream);3200} else {3201bool did_name = false;3202if (!at_this && ss.is_reference()) {3203Symbol* name = ss.as_symbol();3204name->print_value_on(stream);3205did_name = true;3206}3207if (!did_name)3208stream->print("%s", type2name(t));3209}3210if (at_old_sp) {3211stream->print(" (%s of caller)", spname);3212did_old_sp = true;3213}3214stream->cr();3215sig_index += type2size[t];3216arg_index += 1;3217if (!at_this) ss.next();3218}3219if (!did_old_sp) {3220stream->print(" # ");3221stream->move_to(tab1);3222stream->print("[%s+0x%x]", spname, stack_slot_offset);3223stream->print(" (%s of caller)", spname);3224stream->cr();3225}3226}3227}3228}32293230// Returns whether this nmethod has code comments.3231bool nmethod::has_code_comment(address begin, address end) {3232// scopes?3233ScopeDesc* sd = scope_desc_in(begin, end);3234if (sd != NULL) return true;32353236// relocations?3237const char* str = reloc_string_for(begin, end);3238if (str != NULL) return true;32393240// implicit exceptions?3241int cont_offset = ImplicitExceptionTable(this).continuation_offset(begin - code_begin());3242if (cont_offset != 0) return true;32433244return false;3245}32463247void nmethod::print_code_comment_on(outputStream* st, int column, address begin, address end) {3248ImplicitExceptionTable implicit_table(this);3249int pc_offset = begin - code_begin();3250int cont_offset = implicit_table.continuation_offset(pc_offset);3251bool oop_map_required = false;3252if (cont_offset != 0) {3253st->move_to(column, 6, 0);3254if (pc_offset == cont_offset) {3255st->print("; implicit exception: deoptimizes");3256oop_map_required = true;3257} else {3258st->print("; implicit exception: dispatches to " INTPTR_FORMAT, p2i(code_begin() + cont_offset));3259}3260}32613262// Find an oopmap in (begin, end]. We use the odd half-closed3263// interval so that oop maps and scope descs which are tied to the3264// byte after a call are printed with the call itself. OopMaps3265// associated with implicit exceptions are printed with the implicit3266// instruction.3267address base = code_begin();3268ImmutableOopMapSet* oms = oop_maps();3269if (oms != NULL) {3270for (int i = 0, imax = oms->count(); i < imax; i++) {3271const ImmutableOopMapPair* pair = oms->pair_at(i);3272const ImmutableOopMap* om = pair->get_from(oms);3273address pc = base + pair->pc_offset();3274if (pc >= begin) {3275#if INCLUDE_JVMCI3276bool is_implicit_deopt = implicit_table.continuation_offset(pair->pc_offset()) == (uint) pair->pc_offset();3277#else3278bool is_implicit_deopt = false;3279#endif3280if (is_implicit_deopt ? pc == begin : pc > begin && pc <= end) {3281st->move_to(column, 6, 0);3282st->print("; ");3283om->print_on(st);3284oop_map_required = false;3285}3286}3287if (pc > end) {3288break;3289}3290}3291}3292assert(!oop_map_required, "missed oopmap");32933294Thread* thread = Thread::current();32953296// Print any debug info present at this pc.3297ScopeDesc* sd = scope_desc_in(begin, end);3298if (sd != NULL) {3299st->move_to(column, 6, 0);3300if (sd->bci() == SynchronizationEntryBCI) {3301st->print(";*synchronization entry");3302} else if (sd->bci() == AfterBci) {3303st->print(";* method exit (unlocked if synchronized)");3304} else if (sd->bci() == UnwindBci) {3305st->print(";* unwind (locked if synchronized)");3306} else if (sd->bci() == AfterExceptionBci) {3307st->print(";* unwind (unlocked if synchronized)");3308} else if (sd->bci() == UnknownBci) {3309st->print(";* unknown");3310} else if (sd->bci() == InvalidFrameStateBci) {3311st->print(";* invalid frame state");3312} else {3313if (sd->method() == NULL) {3314st->print("method is NULL");3315} else if (sd->method()->is_native()) {3316st->print("method is native");3317} else {3318Bytecodes::Code bc = sd->method()->java_code_at(sd->bci());3319st->print(";*%s", Bytecodes::name(bc));3320switch (bc) {3321case Bytecodes::_invokevirtual:3322case Bytecodes::_invokespecial:3323case Bytecodes::_invokestatic:3324case Bytecodes::_invokeinterface:3325{3326Bytecode_invoke invoke(methodHandle(thread, sd->method()), sd->bci());3327st->print(" ");3328if (invoke.name() != NULL)3329invoke.name()->print_symbol_on(st);3330else3331st->print("<UNKNOWN>");3332break;3333}3334case Bytecodes::_getfield:3335case Bytecodes::_putfield:3336case Bytecodes::_getstatic:3337case Bytecodes::_putstatic:3338{3339Bytecode_field field(methodHandle(thread, sd->method()), sd->bci());3340st->print(" ");3341if (field.name() != NULL)3342field.name()->print_symbol_on(st);3343else3344st->print("<UNKNOWN>");3345}3346default:3347break;3348}3349}3350st->print(" {reexecute=%d rethrow=%d return_oop=%d}", sd->should_reexecute(), sd->rethrow_exception(), sd->return_oop());3351}33523353// Print all scopes3354for (;sd != NULL; sd = sd->sender()) {3355st->move_to(column, 6, 0);3356st->print("; -");3357if (sd->should_reexecute()) {3358st->print(" (reexecute)");3359}3360if (sd->method() == NULL) {3361st->print("method is NULL");3362} else {3363sd->method()->print_short_name(st);3364}3365int lineno = sd->method()->line_number_from_bci(sd->bci());3366if (lineno != -1) {3367st->print("@%d (line %d)", sd->bci(), lineno);3368} else {3369st->print("@%d", sd->bci());3370}3371st->cr();3372}3373}33743375// Print relocation information3376// Prevent memory leak: allocating without ResourceMark.3377ResourceMark rm;3378const char* str = reloc_string_for(begin, end);3379if (str != NULL) {3380if (sd != NULL) st->cr();3381st->move_to(column, 6, 0);3382st->print("; {%s}", str);3383}3384}33853386#endif33873388class DirectNativeCallWrapper: public NativeCallWrapper {3389private:3390NativeCall* _call;33913392public:3393DirectNativeCallWrapper(NativeCall* call) : _call(call) {}33943395virtual address destination() const { return _call->destination(); }3396virtual address instruction_address() const { return _call->instruction_address(); }3397virtual address next_instruction_address() const { return _call->next_instruction_address(); }3398virtual address return_address() const { return _call->return_address(); }33993400virtual address get_resolve_call_stub(bool is_optimized) const {3401if (is_optimized) {3402return SharedRuntime::get_resolve_opt_virtual_call_stub();3403}3404return SharedRuntime::get_resolve_virtual_call_stub();3405}34063407virtual void set_destination_mt_safe(address dest) {3408_call->set_destination_mt_safe(dest);3409}34103411virtual void set_to_interpreted(const methodHandle& method, CompiledICInfo& info) {3412CompiledDirectStaticCall* csc = CompiledDirectStaticCall::at(instruction_address());3413{3414csc->set_to_interpreted(method, info.entry());3415}3416}34173418virtual void verify() const {3419// make sure code pattern is actually a call imm32 instruction3420_call->verify();3421_call->verify_alignment();3422}34233424virtual void verify_resolve_call(address dest) const {3425CodeBlob* db = CodeCache::find_blob_unsafe(dest);3426assert(db != NULL && !db->is_adapter_blob(), "must use stub!");3427}34283429virtual bool is_call_to_interpreted(address dest) const {3430CodeBlob* cb = CodeCache::find_blob(_call->instruction_address());3431return cb->contains(dest);3432}34333434virtual bool is_safe_for_patching() const { return false; }34353436virtual NativeInstruction* get_load_instruction(virtual_call_Relocation* r) const {3437return nativeMovConstReg_at(r->cached_value());3438}34393440virtual void *get_data(NativeInstruction* instruction) const {3441return (void*)((NativeMovConstReg*) instruction)->data();3442}34433444virtual void set_data(NativeInstruction* instruction, intptr_t data) {3445((NativeMovConstReg*) instruction)->set_data(data);3446}3447};34483449NativeCallWrapper* nmethod::call_wrapper_at(address call) const {3450return new DirectNativeCallWrapper((NativeCall*) call);3451}34523453NativeCallWrapper* nmethod::call_wrapper_before(address return_pc) const {3454return new DirectNativeCallWrapper(nativeCall_before(return_pc));3455}34563457address nmethod::call_instruction_address(address pc) const {3458if (NativeCall::is_call_before(pc)) {3459NativeCall *ncall = nativeCall_before(pc);3460return ncall->instruction_address();3461}3462return NULL;3463}34643465CompiledStaticCall* nmethod::compiledStaticCall_at(Relocation* call_site) const {3466return CompiledDirectStaticCall::at(call_site);3467}34683469CompiledStaticCall* nmethod::compiledStaticCall_at(address call_site) const {3470return CompiledDirectStaticCall::at(call_site);3471}34723473CompiledStaticCall* nmethod::compiledStaticCall_before(address return_addr) const {3474return CompiledDirectStaticCall::before(return_addr);3475}34763477#if defined(SUPPORT_DATA_STRUCTS)3478void nmethod::print_value_on(outputStream* st) const {3479st->print("nmethod");3480print_on(st, NULL);3481}3482#endif34833484#ifndef PRODUCT34853486void nmethod::print_calls(outputStream* st) {3487RelocIterator iter(this);3488while (iter.next()) {3489switch (iter.type()) {3490case relocInfo::virtual_call_type:3491case relocInfo::opt_virtual_call_type: {3492CompiledICLocker ml_verify(this);3493CompiledIC_at(&iter)->print();3494break;3495}3496case relocInfo::static_call_type:3497st->print_cr("Static call at " INTPTR_FORMAT, p2i(iter.reloc()->addr()));3498CompiledDirectStaticCall::at(iter.reloc())->print();3499break;3500default:3501break;3502}3503}3504}35053506void nmethod::print_statistics() {3507ttyLocker ttyl;3508if (xtty != NULL) xtty->head("statistics type='nmethod'");3509native_nmethod_stats.print_native_nmethod_stats();3510#ifdef COMPILER13511c1_java_nmethod_stats.print_nmethod_stats("C1");3512#endif3513#ifdef COMPILER23514c2_java_nmethod_stats.print_nmethod_stats("C2");3515#endif3516#if INCLUDE_JVMCI3517jvmci_java_nmethod_stats.print_nmethod_stats("JVMCI");3518#endif3519unknown_java_nmethod_stats.print_nmethod_stats("Unknown");3520DebugInformationRecorder::print_statistics();3521#ifndef PRODUCT3522pc_nmethod_stats.print_pc_stats();3523#endif3524Dependencies::print_statistics();3525if (xtty != NULL) xtty->tail("statistics");3526}35273528#endif // !PRODUCT35293530#if INCLUDE_JVMCI3531void nmethod::update_speculation(JavaThread* thread) {3532jlong speculation = thread->pending_failed_speculation();3533if (speculation != 0) {3534guarantee(jvmci_nmethod_data() != NULL, "failed speculation in nmethod without failed speculation list");3535jvmci_nmethod_data()->add_failed_speculation(this, speculation);3536thread->set_pending_failed_speculation(0);3537}3538}35393540const char* nmethod::jvmci_name() {3541if (jvmci_nmethod_data() != NULL) {3542return jvmci_nmethod_data()->name();3543}3544return NULL;3545}3546#endif354735483549