Path: blob/master/src/hotspot/share/code/codeCache.cpp
64440 views
/*1* Copyright (c) 1997, 2022, 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_io.h"26#include "code/codeBlob.hpp"27#include "code/codeCache.hpp"28#include "code/codeHeapState.hpp"29#include "code/compiledIC.hpp"30#include "code/dependencies.hpp"31#include "code/dependencyContext.hpp"32#include "code/icBuffer.hpp"33#include "code/nmethod.hpp"34#include "code/pcDesc.hpp"35#include "compiler/compilationPolicy.hpp"36#include "compiler/compileBroker.hpp"37#include "compiler/oopMap.hpp"38#include "gc/shared/collectedHeap.hpp"39#include "jfr/jfrEvents.hpp"40#include "logging/log.hpp"41#include "logging/logStream.hpp"42#include "memory/allocation.inline.hpp"43#include "memory/iterator.hpp"44#include "memory/resourceArea.hpp"45#include "memory/universe.hpp"46#include "oops/method.inline.hpp"47#include "oops/objArrayOop.hpp"48#include "oops/oop.inline.hpp"49#include "oops/verifyOopClosure.hpp"50#include "runtime/arguments.hpp"51#include "runtime/atomic.hpp"52#include "runtime/deoptimization.hpp"53#include "runtime/globals_extension.hpp"54#include "runtime/handles.inline.hpp"55#include "runtime/icache.hpp"56#include "runtime/java.hpp"57#include "runtime/mutexLocker.hpp"58#include "runtime/safepointVerifiers.hpp"59#include "runtime/sweeper.hpp"60#include "runtime/vmThread.hpp"61#include "services/memoryService.hpp"62#include "utilities/align.hpp"63#include "utilities/vmError.hpp"64#include "utilities/xmlstream.hpp"65#ifdef COMPILER166#include "c1/c1_Compilation.hpp"67#include "c1/c1_Compiler.hpp"68#endif69#ifdef COMPILER270#include "opto/c2compiler.hpp"71#include "opto/compile.hpp"72#include "opto/node.hpp"73#endif7475// Helper class for printing in CodeCache76class CodeBlob_sizes {77private:78int count;79int total_size;80int header_size;81int code_size;82int stub_size;83int relocation_size;84int scopes_oop_size;85int scopes_metadata_size;86int scopes_data_size;87int scopes_pcs_size;8889public:90CodeBlob_sizes() {91count = 0;92total_size = 0;93header_size = 0;94code_size = 0;95stub_size = 0;96relocation_size = 0;97scopes_oop_size = 0;98scopes_metadata_size = 0;99scopes_data_size = 0;100scopes_pcs_size = 0;101}102103int total() { return total_size; }104bool is_empty() { return count == 0; }105106void print(const char* title) {107tty->print_cr(" #%d %s = %dK (hdr %d%%, loc %d%%, code %d%%, stub %d%%, [oops %d%%, metadata %d%%, data %d%%, pcs %d%%])",108count,109title,110(int)(total() / K),111header_size * 100 / total_size,112relocation_size * 100 / total_size,113code_size * 100 / total_size,114stub_size * 100 / total_size,115scopes_oop_size * 100 / total_size,116scopes_metadata_size * 100 / total_size,117scopes_data_size * 100 / total_size,118scopes_pcs_size * 100 / total_size);119}120121void add(CodeBlob* cb) {122count++;123total_size += cb->size();124header_size += cb->header_size();125relocation_size += cb->relocation_size();126if (cb->is_nmethod()) {127nmethod* nm = cb->as_nmethod_or_null();128code_size += nm->insts_size();129stub_size += nm->stub_size();130131scopes_oop_size += nm->oops_size();132scopes_metadata_size += nm->metadata_size();133scopes_data_size += nm->scopes_data_size();134scopes_pcs_size += nm->scopes_pcs_size();135} else {136code_size += cb->code_size();137}138}139};140141// Iterate over all CodeHeaps142#define FOR_ALL_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _heaps->begin(); heap != _heaps->end(); ++heap)143#define FOR_ALL_NMETHOD_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _nmethod_heaps->begin(); heap != _nmethod_heaps->end(); ++heap)144#define FOR_ALL_ALLOCABLE_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _allocable_heaps->begin(); heap != _allocable_heaps->end(); ++heap)145146// Iterate over all CodeBlobs (cb) on the given CodeHeap147#define FOR_ALL_BLOBS(cb, heap) for (CodeBlob* cb = first_blob(heap); cb != NULL; cb = next_blob(heap, cb))148149address CodeCache::_low_bound = 0;150address CodeCache::_high_bound = 0;151int CodeCache::_number_of_nmethods_with_dependencies = 0;152ExceptionCache* volatile CodeCache::_exception_cache_purge_list = NULL;153154// Initialize arrays of CodeHeap subsets155GrowableArray<CodeHeap*>* CodeCache::_heaps = new(ResourceObj::C_HEAP, mtCode) GrowableArray<CodeHeap*> (CodeBlobType::All, mtCode);156GrowableArray<CodeHeap*>* CodeCache::_compiled_heaps = new(ResourceObj::C_HEAP, mtCode) GrowableArray<CodeHeap*> (CodeBlobType::All, mtCode);157GrowableArray<CodeHeap*>* CodeCache::_nmethod_heaps = new(ResourceObj::C_HEAP, mtCode) GrowableArray<CodeHeap*> (CodeBlobType::All, mtCode);158GrowableArray<CodeHeap*>* CodeCache::_allocable_heaps = new(ResourceObj::C_HEAP, mtCode) GrowableArray<CodeHeap*> (CodeBlobType::All, mtCode);159160void CodeCache::check_heap_sizes(size_t non_nmethod_size, size_t profiled_size, size_t non_profiled_size, size_t cache_size, bool all_set) {161size_t total_size = non_nmethod_size + profiled_size + non_profiled_size;162// Prepare error message163const char* error = "Invalid code heap sizes";164err_msg message("NonNMethodCodeHeapSize (" SIZE_FORMAT "K) + ProfiledCodeHeapSize (" SIZE_FORMAT "K)"165" + NonProfiledCodeHeapSize (" SIZE_FORMAT "K) = " SIZE_FORMAT "K",166non_nmethod_size/K, profiled_size/K, non_profiled_size/K, total_size/K);167168if (total_size > cache_size) {169// Some code heap sizes were explicitly set: total_size must be <= cache_size170message.append(" is greater than ReservedCodeCacheSize (" SIZE_FORMAT "K).", cache_size/K);171vm_exit_during_initialization(error, message);172} else if (all_set && total_size != cache_size) {173// All code heap sizes were explicitly set: total_size must equal cache_size174message.append(" is not equal to ReservedCodeCacheSize (" SIZE_FORMAT "K).", cache_size/K);175vm_exit_during_initialization(error, message);176}177}178179void CodeCache::initialize_heaps() {180bool non_nmethod_set = FLAG_IS_CMDLINE(NonNMethodCodeHeapSize);181bool profiled_set = FLAG_IS_CMDLINE(ProfiledCodeHeapSize);182bool non_profiled_set = FLAG_IS_CMDLINE(NonProfiledCodeHeapSize);183size_t min_size = os::vm_page_size();184size_t cache_size = ReservedCodeCacheSize;185size_t non_nmethod_size = NonNMethodCodeHeapSize;186size_t profiled_size = ProfiledCodeHeapSize;187size_t non_profiled_size = NonProfiledCodeHeapSize;188// Check if total size set via command line flags exceeds the reserved size189check_heap_sizes((non_nmethod_set ? non_nmethod_size : min_size),190(profiled_set ? profiled_size : min_size),191(non_profiled_set ? non_profiled_size : min_size),192cache_size,193non_nmethod_set && profiled_set && non_profiled_set);194195// Determine size of compiler buffers196size_t code_buffers_size = 0;197#ifdef COMPILER1198// C1 temporary code buffers (see Compiler::init_buffer_blob())199const int c1_count = CompilationPolicy::c1_count();200code_buffers_size += c1_count * Compiler::code_buffer_size();201#endif202#ifdef COMPILER2203// C2 scratch buffers (see Compile::init_scratch_buffer_blob())204const int c2_count = CompilationPolicy::c2_count();205// Initial size of constant table (this may be increased if a compiled method needs more space)206code_buffers_size += c2_count * C2Compiler::initial_code_buffer_size();207#endif208209// Increase default non_nmethod_size to account for compiler buffers210if (!non_nmethod_set) {211non_nmethod_size += code_buffers_size;212}213// Calculate default CodeHeap sizes if not set by user214if (!non_nmethod_set && !profiled_set && !non_profiled_set) {215// Check if we have enough space for the non-nmethod code heap216if (cache_size > non_nmethod_size) {217// Use the default value for non_nmethod_size and one half of the218// remaining size for non-profiled and one half for profiled methods219size_t remaining_size = cache_size - non_nmethod_size;220profiled_size = remaining_size / 2;221non_profiled_size = remaining_size - profiled_size;222} else {223// Use all space for the non-nmethod heap and set other heaps to minimal size224non_nmethod_size = cache_size - 2 * min_size;225profiled_size = min_size;226non_profiled_size = min_size;227}228} else if (!non_nmethod_set || !profiled_set || !non_profiled_set) {229// The user explicitly set some code heap sizes. Increase or decrease the (default)230// sizes of the other code heaps accordingly. First adapt non-profiled and profiled231// code heap sizes and then only change non-nmethod code heap size if still necessary.232intx diff_size = cache_size - (non_nmethod_size + profiled_size + non_profiled_size);233if (non_profiled_set) {234if (!profiled_set) {235// Adapt size of profiled code heap236if (diff_size < 0 && ((intx)profiled_size + diff_size) <= 0) {237// Not enough space available, set to minimum size238diff_size += profiled_size - min_size;239profiled_size = min_size;240} else {241profiled_size += diff_size;242diff_size = 0;243}244}245} else if (profiled_set) {246// Adapt size of non-profiled code heap247if (diff_size < 0 && ((intx)non_profiled_size + diff_size) <= 0) {248// Not enough space available, set to minimum size249diff_size += non_profiled_size - min_size;250non_profiled_size = min_size;251} else {252non_profiled_size += diff_size;253diff_size = 0;254}255} else if (non_nmethod_set) {256// Distribute remaining size between profiled and non-profiled code heaps257diff_size = cache_size - non_nmethod_size;258profiled_size = diff_size / 2;259non_profiled_size = diff_size - profiled_size;260diff_size = 0;261}262if (diff_size != 0) {263// Use non-nmethod code heap for remaining space requirements264assert(!non_nmethod_set && ((intx)non_nmethod_size + diff_size) > 0, "sanity");265non_nmethod_size += diff_size;266}267}268269// We do not need the profiled CodeHeap, use all space for the non-profiled CodeHeap270if (!heap_available(CodeBlobType::MethodProfiled)) {271non_profiled_size += profiled_size;272profiled_size = 0;273}274// We do not need the non-profiled CodeHeap, use all space for the non-nmethod CodeHeap275if (!heap_available(CodeBlobType::MethodNonProfiled)) {276non_nmethod_size += non_profiled_size;277non_profiled_size = 0;278}279// Make sure we have enough space for VM internal code280uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3);281if (non_nmethod_size < min_code_cache_size) {282vm_exit_during_initialization(err_msg(283"Not enough space in non-nmethod code heap to run VM: " SIZE_FORMAT "K < " SIZE_FORMAT "K",284non_nmethod_size/K, min_code_cache_size/K));285}286287// Verify sizes and update flag values288assert(non_profiled_size + profiled_size + non_nmethod_size == cache_size, "Invalid code heap sizes");289FLAG_SET_ERGO(NonNMethodCodeHeapSize, non_nmethod_size);290FLAG_SET_ERGO(ProfiledCodeHeapSize, profiled_size);291FLAG_SET_ERGO(NonProfiledCodeHeapSize, non_profiled_size);292293// If large page support is enabled, align code heaps according to large294// page size to make sure that code cache is covered by large pages.295const size_t alignment = MAX2(page_size(false, 8), (size_t) os::vm_allocation_granularity());296non_nmethod_size = align_up(non_nmethod_size, alignment);297profiled_size = align_down(profiled_size, alignment);298299// Reserve one continuous chunk of memory for CodeHeaps and split it into300// parts for the individual heaps. The memory layout looks like this:301// ---------- high -----------302// Non-profiled nmethods303// Profiled nmethods304// Non-nmethods305// ---------- low ------------306ReservedCodeSpace rs = reserve_heap_memory(cache_size);307ReservedSpace non_method_space = rs.first_part(non_nmethod_size);308ReservedSpace rest = rs.last_part(non_nmethod_size);309ReservedSpace profiled_space = rest.first_part(profiled_size);310ReservedSpace non_profiled_space = rest.last_part(profiled_size);311312// Non-nmethods (stubs, adapters, ...)313add_heap(non_method_space, "CodeHeap 'non-nmethods'", CodeBlobType::NonNMethod);314// Tier 2 and tier 3 (profiled) methods315add_heap(profiled_space, "CodeHeap 'profiled nmethods'", CodeBlobType::MethodProfiled);316// Tier 1 and tier 4 (non-profiled) methods and native methods317add_heap(non_profiled_space, "CodeHeap 'non-profiled nmethods'", CodeBlobType::MethodNonProfiled);318}319320size_t CodeCache::page_size(bool aligned, size_t min_pages) {321if (os::can_execute_large_page_memory()) {322if (InitialCodeCacheSize < ReservedCodeCacheSize) {323// Make sure that the page size allows for an incremental commit of the reserved space324min_pages = MAX2(min_pages, (size_t)8);325}326return aligned ? os::page_size_for_region_aligned(ReservedCodeCacheSize, min_pages) :327os::page_size_for_region_unaligned(ReservedCodeCacheSize, min_pages);328} else {329return os::vm_page_size();330}331}332333ReservedCodeSpace CodeCache::reserve_heap_memory(size_t size) {334// Align and reserve space for code cache335const size_t rs_ps = page_size();336const size_t rs_align = MAX2(rs_ps, (size_t) os::vm_allocation_granularity());337const size_t rs_size = align_up(size, rs_align);338ReservedCodeSpace rs(rs_size, rs_align, rs_ps);339if (!rs.is_reserved()) {340vm_exit_during_initialization(err_msg("Could not reserve enough space for code cache (" SIZE_FORMAT "K)",341rs_size/K));342}343344// Initialize bounds345_low_bound = (address)rs.base();346_high_bound = _low_bound + rs.size();347return rs;348}349350// Heaps available for allocation351bool CodeCache::heap_available(int code_blob_type) {352if (!SegmentedCodeCache) {353// No segmentation: use a single code heap354return (code_blob_type == CodeBlobType::All);355} else if (Arguments::is_interpreter_only()) {356// Interpreter only: we don't need any method code heaps357return (code_blob_type == CodeBlobType::NonNMethod);358} else if (CompilerConfig::is_c1_profiling()) {359// Tiered compilation: use all code heaps360return (code_blob_type < CodeBlobType::All);361} else {362// No TieredCompilation: we only need the non-nmethod and non-profiled code heap363return (code_blob_type == CodeBlobType::NonNMethod) ||364(code_blob_type == CodeBlobType::MethodNonProfiled);365}366}367368const char* CodeCache::get_code_heap_flag_name(int code_blob_type) {369switch(code_blob_type) {370case CodeBlobType::NonNMethod:371return "NonNMethodCodeHeapSize";372break;373case CodeBlobType::MethodNonProfiled:374return "NonProfiledCodeHeapSize";375break;376case CodeBlobType::MethodProfiled:377return "ProfiledCodeHeapSize";378break;379}380ShouldNotReachHere();381return NULL;382}383384int CodeCache::code_heap_compare(CodeHeap* const &lhs, CodeHeap* const &rhs) {385if (lhs->code_blob_type() == rhs->code_blob_type()) {386return (lhs > rhs) ? 1 : ((lhs < rhs) ? -1 : 0);387} else {388return lhs->code_blob_type() - rhs->code_blob_type();389}390}391392void CodeCache::add_heap(CodeHeap* heap) {393assert(!Universe::is_fully_initialized(), "late heap addition?");394395_heaps->insert_sorted<code_heap_compare>(heap);396397int type = heap->code_blob_type();398if (code_blob_type_accepts_compiled(type)) {399_compiled_heaps->insert_sorted<code_heap_compare>(heap);400}401if (code_blob_type_accepts_nmethod(type)) {402_nmethod_heaps->insert_sorted<code_heap_compare>(heap);403}404if (code_blob_type_accepts_allocable(type)) {405_allocable_heaps->insert_sorted<code_heap_compare>(heap);406}407}408409void CodeCache::add_heap(ReservedSpace rs, const char* name, int code_blob_type) {410// Check if heap is needed411if (!heap_available(code_blob_type)) {412return;413}414415// Create CodeHeap416CodeHeap* heap = new CodeHeap(name, code_blob_type);417add_heap(heap);418419// Reserve Space420size_t size_initial = MIN2((size_t)InitialCodeCacheSize, rs.size());421size_initial = align_up(size_initial, os::vm_page_size());422if (!heap->reserve(rs, size_initial, CodeCacheSegmentSize)) {423vm_exit_during_initialization(err_msg("Could not reserve enough space in %s (" SIZE_FORMAT "K)",424heap->name(), size_initial/K));425}426427// Register the CodeHeap428MemoryService::add_code_heap_memory_pool(heap, name);429}430431CodeHeap* CodeCache::get_code_heap_containing(void* start) {432FOR_ALL_HEAPS(heap) {433if ((*heap)->contains(start)) {434return *heap;435}436}437return NULL;438}439440CodeHeap* CodeCache::get_code_heap(const CodeBlob* cb) {441assert(cb != NULL, "CodeBlob is null");442FOR_ALL_HEAPS(heap) {443if ((*heap)->contains_blob(cb)) {444return *heap;445}446}447ShouldNotReachHere();448return NULL;449}450451CodeHeap* CodeCache::get_code_heap(int code_blob_type) {452FOR_ALL_HEAPS(heap) {453if ((*heap)->accepts(code_blob_type)) {454return *heap;455}456}457return NULL;458}459460CodeBlob* CodeCache::first_blob(CodeHeap* heap) {461assert_locked_or_safepoint(CodeCache_lock);462assert(heap != NULL, "heap is null");463return (CodeBlob*)heap->first();464}465466CodeBlob* CodeCache::first_blob(int code_blob_type) {467if (heap_available(code_blob_type)) {468return first_blob(get_code_heap(code_blob_type));469} else {470return NULL;471}472}473474CodeBlob* CodeCache::next_blob(CodeHeap* heap, CodeBlob* cb) {475assert_locked_or_safepoint(CodeCache_lock);476assert(heap != NULL, "heap is null");477return (CodeBlob*)heap->next(cb);478}479480/**481* Do not seize the CodeCache lock here--if the caller has not482* already done so, we are going to lose bigtime, since the code483* cache will contain a garbage CodeBlob until the caller can484* run the constructor for the CodeBlob subclass he is busy485* instantiating.486*/487CodeBlob* CodeCache::allocate(int size, int code_blob_type, bool handle_alloc_failure, int orig_code_blob_type) {488// Possibly wakes up the sweeper thread.489NMethodSweeper::report_allocation();490assert_locked_or_safepoint(CodeCache_lock);491assert(size > 0, "Code cache allocation request must be > 0 but is %d", size);492if (size <= 0) {493return NULL;494}495CodeBlob* cb = NULL;496497// Get CodeHeap for the given CodeBlobType498CodeHeap* heap = get_code_heap(code_blob_type);499assert(heap != NULL, "heap is null");500501while (true) {502cb = (CodeBlob*)heap->allocate(size);503if (cb != NULL) break;504if (!heap->expand_by(CodeCacheExpansionSize)) {505// Save original type for error reporting506if (orig_code_blob_type == CodeBlobType::All) {507orig_code_blob_type = code_blob_type;508}509// Expansion failed510if (SegmentedCodeCache) {511// Fallback solution: Try to store code in another code heap.512// NonNMethod -> MethodNonProfiled -> MethodProfiled (-> MethodNonProfiled)513// Note that in the sweeper, we check the reverse_free_ratio of the code heap514// and force stack scanning if less than 10% of the entire code cache are free.515int type = code_blob_type;516switch (type) {517case CodeBlobType::NonNMethod:518type = CodeBlobType::MethodNonProfiled;519break;520case CodeBlobType::MethodNonProfiled:521type = CodeBlobType::MethodProfiled;522break;523case CodeBlobType::MethodProfiled:524// Avoid loop if we already tried that code heap525if (type == orig_code_blob_type) {526type = CodeBlobType::MethodNonProfiled;527}528break;529}530if (type != code_blob_type && type != orig_code_blob_type && heap_available(type)) {531if (PrintCodeCacheExtension) {532tty->print_cr("Extension of %s failed. Trying to allocate in %s.",533heap->name(), get_code_heap(type)->name());534}535return allocate(size, type, handle_alloc_failure, orig_code_blob_type);536}537}538if (handle_alloc_failure) {539MutexUnlocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);540CompileBroker::handle_full_code_cache(orig_code_blob_type);541}542return NULL;543}544if (PrintCodeCacheExtension) {545ResourceMark rm;546if (_nmethod_heaps->length() >= 1) {547tty->print("%s", heap->name());548} else {549tty->print("CodeCache");550}551tty->print_cr(" extended to [" INTPTR_FORMAT ", " INTPTR_FORMAT "] (" SSIZE_FORMAT " bytes)",552(intptr_t)heap->low_boundary(), (intptr_t)heap->high(),553(address)heap->high() - (address)heap->low_boundary());554}555}556print_trace("allocation", cb, size);557return cb;558}559560void CodeCache::free(CodeBlob* cb) {561assert_locked_or_safepoint(CodeCache_lock);562CodeHeap* heap = get_code_heap(cb);563print_trace("free", cb);564if (cb->is_nmethod()) {565nmethod* ptr = (nmethod *)cb;566heap->set_nmethod_count(heap->nmethod_count() - 1);567if (ptr->has_dependencies()) {568_number_of_nmethods_with_dependencies--;569}570ptr->free_native_invokers();571}572if (cb->is_adapter_blob()) {573heap->set_adapter_count(heap->adapter_count() - 1);574}575576// Get heap for given CodeBlob and deallocate577get_code_heap(cb)->deallocate(cb);578579assert(heap->blob_count() >= 0, "sanity check");580}581582void CodeCache::free_unused_tail(CodeBlob* cb, size_t used) {583assert_locked_or_safepoint(CodeCache_lock);584guarantee(cb->is_buffer_blob() && strncmp("Interpreter", cb->name(), 11) == 0, "Only possible for interpreter!");585print_trace("free_unused_tail", cb);586587// We also have to account for the extra space (i.e. header) used by the CodeBlob588// which provides the memory (see BufferBlob::create() in codeBlob.cpp).589used += CodeBlob::align_code_offset(cb->header_size());590591// Get heap for given CodeBlob and deallocate its unused tail592get_code_heap(cb)->deallocate_tail(cb, used);593// Adjust the sizes of the CodeBlob594cb->adjust_size(used);595}596597void CodeCache::commit(CodeBlob* cb) {598// this is called by nmethod::nmethod, which must already own CodeCache_lock599assert_locked_or_safepoint(CodeCache_lock);600CodeHeap* heap = get_code_heap(cb);601if (cb->is_nmethod()) {602heap->set_nmethod_count(heap->nmethod_count() + 1);603if (((nmethod *)cb)->has_dependencies()) {604_number_of_nmethods_with_dependencies++;605}606}607if (cb->is_adapter_blob()) {608heap->set_adapter_count(heap->adapter_count() + 1);609}610611// flush the hardware I-cache612ICache::invalidate_range(cb->content_begin(), cb->content_size());613}614615bool CodeCache::contains(void *p) {616// S390 uses contains() in current_frame(), which is used before617// code cache initialization if NativeMemoryTracking=detail is set.618S390_ONLY(if (_heaps == NULL) return false;)619// It should be ok to call contains without holding a lock.620FOR_ALL_HEAPS(heap) {621if ((*heap)->contains(p)) {622return true;623}624}625return false;626}627628bool CodeCache::contains(nmethod *nm) {629return contains((void *)nm);630}631632static bool is_in_asgct() {633Thread* current_thread = Thread::current_or_null_safe();634return current_thread != NULL && current_thread->is_Java_thread() && current_thread->as_Java_thread()->in_asgct();635}636637// This method is safe to call without holding the CodeCache_lock, as long as a dead CodeBlob is not638// looked up (i.e., one that has been marked for deletion). It only depends on the _segmap to contain639// valid indices, which it will always do, as long as the CodeBlob is not in the process of being recycled.640CodeBlob* CodeCache::find_blob(void* start) {641CodeBlob* result = find_blob_unsafe(start);642// We could potentially look up non_entrant methods643bool is_zombie = result != NULL && result->is_zombie();644bool is_result_safe = !is_zombie || result->is_locked_by_vm() || VMError::is_error_reported();645guarantee(is_result_safe || is_in_asgct(), "unsafe access to zombie method");646// When in ASGCT the previous gurantee will pass for a zombie method but we still don't want that code blob returned in order647// to minimize the chance of accessing dead memory648return is_result_safe ? result : NULL;649}650651// Lookup that does not fail if you lookup a zombie method (if you call this, be sure to know652// what you are doing)653CodeBlob* CodeCache::find_blob_unsafe(void* start) {654// NMT can walk the stack before code cache is created655if (_heaps != NULL) {656CodeHeap* heap = get_code_heap_containing(start);657if (heap != NULL) {658return heap->find_blob_unsafe(start);659}660}661return NULL;662}663664nmethod* CodeCache::find_nmethod(void* start) {665CodeBlob* cb = find_blob(start);666assert(cb->is_nmethod(), "did not find an nmethod");667return (nmethod*)cb;668}669670void CodeCache::blobs_do(void f(CodeBlob* nm)) {671assert_locked_or_safepoint(CodeCache_lock);672FOR_ALL_HEAPS(heap) {673FOR_ALL_BLOBS(cb, *heap) {674f(cb);675}676}677}678679void CodeCache::nmethods_do(void f(nmethod* nm)) {680assert_locked_or_safepoint(CodeCache_lock);681NMethodIterator iter(NMethodIterator::all_blobs);682while(iter.next()) {683f(iter.method());684}685}686687void CodeCache::metadata_do(MetadataClosure* f) {688assert_locked_or_safepoint(CodeCache_lock);689NMethodIterator iter(NMethodIterator::only_alive);690while(iter.next()) {691iter.method()->metadata_do(f);692}693}694695int CodeCache::alignment_unit() {696return (int)_heaps->first()->alignment_unit();697}698699int CodeCache::alignment_offset() {700return (int)_heaps->first()->alignment_offset();701}702703// Mark nmethods for unloading if they contain otherwise unreachable oops.704void CodeCache::do_unloading(BoolObjectClosure* is_alive, bool unloading_occurred) {705assert_locked_or_safepoint(CodeCache_lock);706UnloadingScope scope(is_alive);707CompiledMethodIterator iter(CompiledMethodIterator::only_alive);708while(iter.next()) {709iter.method()->do_unloading(unloading_occurred);710}711}712713void CodeCache::blobs_do(CodeBlobClosure* f) {714assert_locked_or_safepoint(CodeCache_lock);715FOR_ALL_ALLOCABLE_HEAPS(heap) {716FOR_ALL_BLOBS(cb, *heap) {717if (cb->is_alive()) {718f->do_code_blob(cb);719#ifdef ASSERT720if (cb->is_nmethod()) {721Universe::heap()->verify_nmethod((nmethod*)cb);722}723#endif //ASSERT724}725}726}727}728729void CodeCache::verify_clean_inline_caches() {730#ifdef ASSERT731NMethodIterator iter(NMethodIterator::only_alive_and_not_unloading);732while(iter.next()) {733nmethod* nm = iter.method();734assert(!nm->is_unloaded(), "Tautology");735nm->verify_clean_inline_caches();736nm->verify();737}738#endif739}740741void CodeCache::verify_icholder_relocations() {742#ifdef ASSERT743// make sure that we aren't leaking icholders744int count = 0;745FOR_ALL_HEAPS(heap) {746FOR_ALL_BLOBS(cb, *heap) {747CompiledMethod *nm = cb->as_compiled_method_or_null();748if (nm != NULL) {749count += nm->verify_icholder_relocations();750}751}752}753assert(count + InlineCacheBuffer::pending_icholder_count() + CompiledICHolder::live_not_claimed_count() ==754CompiledICHolder::live_count(), "must agree");755#endif756}757758// Defer freeing of concurrently cleaned ExceptionCache entries until759// after a global handshake operation.760void CodeCache::release_exception_cache(ExceptionCache* entry) {761if (SafepointSynchronize::is_at_safepoint()) {762delete entry;763} else {764for (;;) {765ExceptionCache* purge_list_head = Atomic::load(&_exception_cache_purge_list);766entry->set_purge_list_next(purge_list_head);767if (Atomic::cmpxchg(&_exception_cache_purge_list, purge_list_head, entry) == purge_list_head) {768break;769}770}771}772}773774// Delete exception caches that have been concurrently unlinked,775// followed by a global handshake operation.776void CodeCache::purge_exception_caches() {777ExceptionCache* curr = _exception_cache_purge_list;778while (curr != NULL) {779ExceptionCache* next = curr->purge_list_next();780delete curr;781curr = next;782}783_exception_cache_purge_list = NULL;784}785786uint8_t CodeCache::_unloading_cycle = 1;787788void CodeCache::increment_unloading_cycle() {789// 2-bit value (see IsUnloadingState in nmethod.cpp for details)790// 0 is reserved for new methods.791_unloading_cycle = (_unloading_cycle + 1) % 4;792if (_unloading_cycle == 0) {793_unloading_cycle = 1;794}795}796797CodeCache::UnloadingScope::UnloadingScope(BoolObjectClosure* is_alive)798: _is_unloading_behaviour(is_alive)799{800_saved_behaviour = IsUnloadingBehaviour::current();801IsUnloadingBehaviour::set_current(&_is_unloading_behaviour);802increment_unloading_cycle();803DependencyContext::cleaning_start();804}805806CodeCache::UnloadingScope::~UnloadingScope() {807IsUnloadingBehaviour::set_current(_saved_behaviour);808DependencyContext::cleaning_end();809}810811void CodeCache::verify_oops() {812MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);813VerifyOopClosure voc;814NMethodIterator iter(NMethodIterator::only_alive_and_not_unloading);815while(iter.next()) {816nmethod* nm = iter.method();817nm->oops_do(&voc);818nm->verify_oop_relocations();819}820}821822int CodeCache::blob_count(int code_blob_type) {823CodeHeap* heap = get_code_heap(code_blob_type);824return (heap != NULL) ? heap->blob_count() : 0;825}826827int CodeCache::blob_count() {828int count = 0;829FOR_ALL_HEAPS(heap) {830count += (*heap)->blob_count();831}832return count;833}834835int CodeCache::nmethod_count(int code_blob_type) {836CodeHeap* heap = get_code_heap(code_blob_type);837return (heap != NULL) ? heap->nmethod_count() : 0;838}839840int CodeCache::nmethod_count() {841int count = 0;842FOR_ALL_NMETHOD_HEAPS(heap) {843count += (*heap)->nmethod_count();844}845return count;846}847848int CodeCache::adapter_count(int code_blob_type) {849CodeHeap* heap = get_code_heap(code_blob_type);850return (heap != NULL) ? heap->adapter_count() : 0;851}852853int CodeCache::adapter_count() {854int count = 0;855FOR_ALL_HEAPS(heap) {856count += (*heap)->adapter_count();857}858return count;859}860861address CodeCache::low_bound(int code_blob_type) {862CodeHeap* heap = get_code_heap(code_blob_type);863return (heap != NULL) ? (address)heap->low_boundary() : NULL;864}865866address CodeCache::high_bound(int code_blob_type) {867CodeHeap* heap = get_code_heap(code_blob_type);868return (heap != NULL) ? (address)heap->high_boundary() : NULL;869}870871size_t CodeCache::capacity() {872size_t cap = 0;873FOR_ALL_ALLOCABLE_HEAPS(heap) {874cap += (*heap)->capacity();875}876return cap;877}878879size_t CodeCache::unallocated_capacity(int code_blob_type) {880CodeHeap* heap = get_code_heap(code_blob_type);881return (heap != NULL) ? heap->unallocated_capacity() : 0;882}883884size_t CodeCache::unallocated_capacity() {885size_t unallocated_cap = 0;886FOR_ALL_ALLOCABLE_HEAPS(heap) {887unallocated_cap += (*heap)->unallocated_capacity();888}889return unallocated_cap;890}891892size_t CodeCache::max_capacity() {893size_t max_cap = 0;894FOR_ALL_ALLOCABLE_HEAPS(heap) {895max_cap += (*heap)->max_capacity();896}897return max_cap;898}899900901// Returns the reverse free ratio. E.g., if 25% (1/4) of the code cache902// is free, reverse_free_ratio() returns 4.903// Since code heap for each type of code blobs falls forward to the next904// type of code heap, return the reverse free ratio for the entire905// code cache.906double CodeCache::reverse_free_ratio() {907double unallocated = MAX2((double)unallocated_capacity(), 1.0); // Avoid division by 0;908double max = (double)max_capacity();909double result = max / unallocated;910assert (max >= unallocated, "Must be");911assert (result >= 1.0, "reverse_free_ratio must be at least 1. It is %f", result);912return result;913}914915size_t CodeCache::bytes_allocated_in_freelists() {916size_t allocated_bytes = 0;917FOR_ALL_ALLOCABLE_HEAPS(heap) {918allocated_bytes += (*heap)->allocated_in_freelist();919}920return allocated_bytes;921}922923int CodeCache::allocated_segments() {924int number_of_segments = 0;925FOR_ALL_ALLOCABLE_HEAPS(heap) {926number_of_segments += (*heap)->allocated_segments();927}928return number_of_segments;929}930931size_t CodeCache::freelists_length() {932size_t length = 0;933FOR_ALL_ALLOCABLE_HEAPS(heap) {934length += (*heap)->freelist_length();935}936return length;937}938939void icache_init();940941void CodeCache::initialize() {942assert(CodeCacheSegmentSize >= (uintx)CodeEntryAlignment, "CodeCacheSegmentSize must be large enough to align entry points");943#ifdef COMPILER2944assert(CodeCacheSegmentSize >= (uintx)OptoLoopAlignment, "CodeCacheSegmentSize must be large enough to align inner loops");945#endif946assert(CodeCacheSegmentSize >= sizeof(jdouble), "CodeCacheSegmentSize must be large enough to align constants");947// This was originally just a check of the alignment, causing failure, instead, round948// the code cache to the page size. In particular, Solaris is moving to a larger949// default page size.950CodeCacheExpansionSize = align_up(CodeCacheExpansionSize, os::vm_page_size());951952if (SegmentedCodeCache) {953// Use multiple code heaps954initialize_heaps();955} else {956// Use a single code heap957FLAG_SET_ERGO(NonNMethodCodeHeapSize, 0);958FLAG_SET_ERGO(ProfiledCodeHeapSize, 0);959FLAG_SET_ERGO(NonProfiledCodeHeapSize, 0);960ReservedCodeSpace rs = reserve_heap_memory(ReservedCodeCacheSize);961add_heap(rs, "CodeCache", CodeBlobType::All);962}963964// Initialize ICache flush mechanism965// This service is needed for os::register_code_area966icache_init();967968// Give OS a chance to register generated code area.969// This is used on Windows 64 bit platforms to register970// Structured Exception Handlers for our generated code.971os::register_code_area((char*)low_bound(), (char*)high_bound());972}973974void codeCache_init() {975CodeCache::initialize();976}977978//------------------------------------------------------------------------------------------------979980int CodeCache::number_of_nmethods_with_dependencies() {981return _number_of_nmethods_with_dependencies;982}983984void CodeCache::clear_inline_caches() {985assert_locked_or_safepoint(CodeCache_lock);986CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);987while(iter.next()) {988iter.method()->clear_inline_caches();989}990}991992void CodeCache::cleanup_inline_caches() {993assert_locked_or_safepoint(CodeCache_lock);994NMethodIterator iter(NMethodIterator::only_alive_and_not_unloading);995while(iter.next()) {996iter.method()->cleanup_inline_caches(/*clean_all=*/true);997}998}9991000// Keeps track of time spent for checking dependencies1001NOT_PRODUCT(static elapsedTimer dependentCheckTime;)10021003int CodeCache::mark_for_deoptimization(KlassDepChange& changes) {1004MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);1005int number_of_marked_CodeBlobs = 0;10061007// search the hierarchy looking for nmethods which are affected by the loading of this class10081009// then search the interfaces this class implements looking for nmethods1010// which might be dependent of the fact that an interface only had one1011// implementor.1012// nmethod::check_all_dependencies works only correctly, if no safepoint1013// can happen1014NoSafepointVerifier nsv;1015for (DepChange::ContextStream str(changes, nsv); str.next(); ) {1016Klass* d = str.klass();1017number_of_marked_CodeBlobs += InstanceKlass::cast(d)->mark_dependent_nmethods(changes);1018}10191020#ifndef PRODUCT1021if (VerifyDependencies) {1022// Object pointers are used as unique identifiers for dependency arguments. This1023// is only possible if no safepoint, i.e., GC occurs during the verification code.1024dependentCheckTime.start();1025nmethod::check_all_dependencies(changes);1026dependentCheckTime.stop();1027}1028#endif10291030return number_of_marked_CodeBlobs;1031}10321033CompiledMethod* CodeCache::find_compiled(void* start) {1034CodeBlob *cb = find_blob(start);1035assert(cb == NULL || cb->is_compiled(), "did not find an compiled_method");1036return (CompiledMethod*)cb;1037}10381039#if INCLUDE_JVMTI1040// RedefineClasses support for saving nmethods that are dependent on "old" methods.1041// We don't really expect this table to grow very large. If it does, it can become a hashtable.1042static GrowableArray<CompiledMethod*>* old_compiled_method_table = NULL;10431044static void add_to_old_table(CompiledMethod* c) {1045if (old_compiled_method_table == NULL) {1046old_compiled_method_table = new (ResourceObj::C_HEAP, mtCode) GrowableArray<CompiledMethod*>(100, mtCode);1047}1048old_compiled_method_table->push(c);1049}10501051static void reset_old_method_table() {1052if (old_compiled_method_table != NULL) {1053delete old_compiled_method_table;1054old_compiled_method_table = NULL;1055}1056}10571058// Remove this method when zombied or unloaded.1059void CodeCache::unregister_old_nmethod(CompiledMethod* c) {1060assert_lock_strong(CodeCache_lock);1061if (old_compiled_method_table != NULL) {1062int index = old_compiled_method_table->find(c);1063if (index != -1) {1064old_compiled_method_table->delete_at(index);1065}1066}1067}10681069void CodeCache::old_nmethods_do(MetadataClosure* f) {1070// Walk old method table and mark those on stack.1071int length = 0;1072if (old_compiled_method_table != NULL) {1073length = old_compiled_method_table->length();1074for (int i = 0; i < length; i++) {1075CompiledMethod* cm = old_compiled_method_table->at(i);1076// Only walk alive nmethods, the dead ones will get removed by the sweeper or GC.1077if (cm->is_alive() && !cm->is_unloading()) {1078old_compiled_method_table->at(i)->metadata_do(f);1079}1080}1081}1082log_debug(redefine, class, nmethod)("Walked %d nmethods for mark_on_stack", length);1083}10841085// Just marks the methods in this class as needing deoptimization1086void CodeCache::mark_for_evol_deoptimization(InstanceKlass* dependee) {1087assert(SafepointSynchronize::is_at_safepoint(), "Can only do this at a safepoint!");1088}108910901091// Walk compiled methods and mark dependent methods for deoptimization.1092int CodeCache::mark_dependents_for_evol_deoptimization() {1093assert(SafepointSynchronize::is_at_safepoint(), "Can only do this at a safepoint!");1094// Each redefinition creates a new set of nmethods that have references to "old" Methods1095// So delete old method table and create a new one.1096reset_old_method_table();10971098int number_of_marked_CodeBlobs = 0;1099CompiledMethodIterator iter(CompiledMethodIterator::only_alive);1100while(iter.next()) {1101CompiledMethod* nm = iter.method();1102// Walk all alive nmethods to check for old Methods.1103// This includes methods whose inline caches point to old methods, so1104// inline cache clearing is unnecessary.1105if (nm->has_evol_metadata()) {1106nm->mark_for_deoptimization();1107add_to_old_table(nm);1108number_of_marked_CodeBlobs++;1109}1110}11111112// return total count of nmethods marked for deoptimization, if zero the caller1113// can skip deoptimization1114return number_of_marked_CodeBlobs;1115}11161117void CodeCache::mark_all_nmethods_for_evol_deoptimization() {1118assert(SafepointSynchronize::is_at_safepoint(), "Can only do this at a safepoint!");1119CompiledMethodIterator iter(CompiledMethodIterator::only_alive);1120while(iter.next()) {1121CompiledMethod* nm = iter.method();1122if (!nm->method()->is_method_handle_intrinsic()) {1123nm->mark_for_deoptimization();1124if (nm->has_evol_metadata()) {1125add_to_old_table(nm);1126}1127}1128}1129}11301131// Flushes compiled methods dependent on redefined classes, that have already been1132// marked for deoptimization.1133void CodeCache::flush_evol_dependents() {1134assert(SafepointSynchronize::is_at_safepoint(), "Can only do this at a safepoint!");11351136// CodeCache can only be updated by a thread_in_VM and they will all be1137// stopped during the safepoint so CodeCache will be safe to update without1138// holding the CodeCache_lock.11391140// At least one nmethod has been marked for deoptimization11411142Deoptimization::deoptimize_all_marked();1143}1144#endif // INCLUDE_JVMTI11451146// Mark methods for deopt (if safe or possible).1147void CodeCache::mark_all_nmethods_for_deoptimization() {1148MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);1149CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);1150while(iter.next()) {1151CompiledMethod* nm = iter.method();1152if (!nm->is_native_method()) {1153nm->mark_for_deoptimization();1154}1155}1156}11571158int CodeCache::mark_for_deoptimization(Method* dependee) {1159MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);1160int number_of_marked_CodeBlobs = 0;11611162CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);1163while(iter.next()) {1164CompiledMethod* nm = iter.method();1165if (nm->is_dependent_on_method(dependee)) {1166ResourceMark rm;1167nm->mark_for_deoptimization();1168number_of_marked_CodeBlobs++;1169}1170}11711172return number_of_marked_CodeBlobs;1173}11741175void CodeCache::make_marked_nmethods_not_entrant() {1176assert_locked_or_safepoint(CodeCache_lock);1177CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);1178while(iter.next()) {1179CompiledMethod* nm = iter.method();1180if (nm->is_marked_for_deoptimization()) {1181nm->make_not_entrant();1182}1183}1184}11851186// Flushes compiled methods dependent on dependee.1187void CodeCache::flush_dependents_on(InstanceKlass* dependee) {1188assert_lock_strong(Compile_lock);11891190if (number_of_nmethods_with_dependencies() == 0) return;11911192int marked = 0;1193if (dependee->is_linked()) {1194// Class initialization state change.1195KlassInitDepChange changes(dependee);1196marked = mark_for_deoptimization(changes);1197} else {1198// New class is loaded.1199NewKlassDepChange changes(dependee);1200marked = mark_for_deoptimization(changes);1201}12021203if (marked > 0) {1204// At least one nmethod has been marked for deoptimization1205Deoptimization::deoptimize_all_marked();1206}1207}12081209// Flushes compiled methods dependent on dependee1210void CodeCache::flush_dependents_on_method(const methodHandle& m_h) {1211// --- Compile_lock is not held. However we are at a safepoint.1212assert_locked_or_safepoint(Compile_lock);12131214// Compute the dependent nmethods1215if (mark_for_deoptimization(m_h()) > 0) {1216Deoptimization::deoptimize_all_marked();1217}1218}12191220void CodeCache::verify() {1221assert_locked_or_safepoint(CodeCache_lock);1222FOR_ALL_HEAPS(heap) {1223(*heap)->verify();1224FOR_ALL_BLOBS(cb, *heap) {1225if (cb->is_alive()) {1226cb->verify();1227}1228}1229}1230}12311232// A CodeHeap is full. Print out warning and report event.1233PRAGMA_DIAG_PUSH1234PRAGMA_FORMAT_NONLITERAL_IGNORED1235void CodeCache::report_codemem_full(int code_blob_type, bool print) {1236// Get nmethod heap for the given CodeBlobType and build CodeCacheFull event1237CodeHeap* heap = get_code_heap(code_blob_type);1238assert(heap != NULL, "heap is null");12391240if ((heap->full_count() == 0) || print) {1241// Not yet reported for this heap, report1242if (SegmentedCodeCache) {1243ResourceMark rm;1244stringStream msg1_stream, msg2_stream;1245msg1_stream.print("%s is full. Compiler has been disabled.",1246get_code_heap_name(code_blob_type));1247msg2_stream.print("Try increasing the code heap size using -XX:%s=",1248get_code_heap_flag_name(code_blob_type));1249const char *msg1 = msg1_stream.as_string();1250const char *msg2 = msg2_stream.as_string();12511252log_warning(codecache)("%s", msg1);1253log_warning(codecache)("%s", msg2);1254warning("%s", msg1);1255warning("%s", msg2);1256} else {1257const char *msg1 = "CodeCache is full. Compiler has been disabled.";1258const char *msg2 = "Try increasing the code cache size using -XX:ReservedCodeCacheSize=";12591260log_warning(codecache)("%s", msg1);1261log_warning(codecache)("%s", msg2);1262warning("%s", msg1);1263warning("%s", msg2);1264}1265ResourceMark rm;1266stringStream s;1267// Dump code cache into a buffer before locking the tty.1268{1269MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);1270print_summary(&s);1271}1272{1273ttyLocker ttyl;1274tty->print("%s", s.as_string());1275}12761277if (heap->full_count() == 0) {1278if (PrintCodeHeapAnalytics) {1279CompileBroker::print_heapinfo(tty, "all", 4096); // details, may be a lot!1280}1281}1282}12831284heap->report_full();12851286EventCodeCacheFull event;1287if (event.should_commit()) {1288event.set_codeBlobType((u1)code_blob_type);1289event.set_startAddress((u8)heap->low_boundary());1290event.set_commitedTopAddress((u8)heap->high());1291event.set_reservedTopAddress((u8)heap->high_boundary());1292event.set_entryCount(heap->blob_count());1293event.set_methodCount(heap->nmethod_count());1294event.set_adaptorCount(heap->adapter_count());1295event.set_unallocatedCapacity(heap->unallocated_capacity());1296event.set_fullCount(heap->full_count());1297event.commit();1298}1299}1300PRAGMA_DIAG_POP13011302void CodeCache::print_memory_overhead() {1303size_t wasted_bytes = 0;1304FOR_ALL_ALLOCABLE_HEAPS(heap) {1305CodeHeap* curr_heap = *heap;1306for (CodeBlob* cb = (CodeBlob*)curr_heap->first(); cb != NULL; cb = (CodeBlob*)curr_heap->next(cb)) {1307HeapBlock* heap_block = ((HeapBlock*)cb) - 1;1308wasted_bytes += heap_block->length() * CodeCacheSegmentSize - cb->size();1309}1310}1311// Print bytes that are allocated in the freelist1312ttyLocker ttl;1313tty->print_cr("Number of elements in freelist: " SSIZE_FORMAT, freelists_length());1314tty->print_cr("Allocated in freelist: " SSIZE_FORMAT "kB", bytes_allocated_in_freelists()/K);1315tty->print_cr("Unused bytes in CodeBlobs: " SSIZE_FORMAT "kB", (wasted_bytes/K));1316tty->print_cr("Segment map size: " SSIZE_FORMAT "kB", allocated_segments()/K); // 1 byte per segment1317}13181319//------------------------------------------------------------------------------------------------1320// Non-product version13211322#ifndef PRODUCT13231324void CodeCache::print_trace(const char* event, CodeBlob* cb, int size) {1325if (PrintCodeCache2) { // Need to add a new flag1326ResourceMark rm;1327if (size == 0) size = cb->size();1328tty->print_cr("CodeCache %s: addr: " INTPTR_FORMAT ", size: 0x%x", event, p2i(cb), size);1329}1330}13311332void CodeCache::print_internals() {1333int nmethodCount = 0;1334int runtimeStubCount = 0;1335int adapterCount = 0;1336int deoptimizationStubCount = 0;1337int uncommonTrapStubCount = 0;1338int bufferBlobCount = 0;1339int total = 0;1340int nmethodAlive = 0;1341int nmethodNotEntrant = 0;1342int nmethodZombie = 0;1343int nmethodUnloaded = 0;1344int nmethodJava = 0;1345int nmethodNative = 0;1346int max_nm_size = 0;1347ResourceMark rm;13481349int i = 0;1350FOR_ALL_ALLOCABLE_HEAPS(heap) {1351if ((_nmethod_heaps->length() >= 1) && Verbose) {1352tty->print_cr("-- %s --", (*heap)->name());1353}1354FOR_ALL_BLOBS(cb, *heap) {1355total++;1356if (cb->is_nmethod()) {1357nmethod* nm = (nmethod*)cb;13581359if (Verbose && nm->method() != NULL) {1360ResourceMark rm;1361char *method_name = nm->method()->name_and_sig_as_C_string();1362tty->print("%s", method_name);1363if(nm->is_alive()) { tty->print_cr(" alive"); }1364if(nm->is_not_entrant()) { tty->print_cr(" not-entrant"); }1365if(nm->is_zombie()) { tty->print_cr(" zombie"); }1366}13671368nmethodCount++;13691370if(nm->is_alive()) { nmethodAlive++; }1371if(nm->is_not_entrant()) { nmethodNotEntrant++; }1372if(nm->is_zombie()) { nmethodZombie++; }1373if(nm->is_unloaded()) { nmethodUnloaded++; }1374if(nm->method() != NULL && nm->is_native_method()) { nmethodNative++; }13751376if(nm->method() != NULL && nm->is_java_method()) {1377nmethodJava++;1378max_nm_size = MAX2(max_nm_size, nm->size());1379}1380} else if (cb->is_runtime_stub()) {1381runtimeStubCount++;1382} else if (cb->is_deoptimization_stub()) {1383deoptimizationStubCount++;1384} else if (cb->is_uncommon_trap_stub()) {1385uncommonTrapStubCount++;1386} else if (cb->is_adapter_blob()) {1387adapterCount++;1388} else if (cb->is_buffer_blob()) {1389bufferBlobCount++;1390}1391}1392}13931394int bucketSize = 512;1395int bucketLimit = max_nm_size / bucketSize + 1;1396int *buckets = NEW_C_HEAP_ARRAY(int, bucketLimit, mtCode);1397memset(buckets, 0, sizeof(int) * bucketLimit);13981399NMethodIterator iter(NMethodIterator::all_blobs);1400while(iter.next()) {1401nmethod* nm = iter.method();1402if(nm->method() != NULL && nm->is_java_method()) {1403buckets[nm->size() / bucketSize]++;1404}1405}14061407tty->print_cr("Code Cache Entries (total of %d)",total);1408tty->print_cr("-------------------------------------------------");1409tty->print_cr("nmethods: %d",nmethodCount);1410tty->print_cr("\talive: %d",nmethodAlive);1411tty->print_cr("\tnot_entrant: %d",nmethodNotEntrant);1412tty->print_cr("\tzombie: %d",nmethodZombie);1413tty->print_cr("\tunloaded: %d",nmethodUnloaded);1414tty->print_cr("\tjava: %d",nmethodJava);1415tty->print_cr("\tnative: %d",nmethodNative);1416tty->print_cr("runtime_stubs: %d",runtimeStubCount);1417tty->print_cr("adapters: %d",adapterCount);1418tty->print_cr("buffer blobs: %d",bufferBlobCount);1419tty->print_cr("deoptimization_stubs: %d",deoptimizationStubCount);1420tty->print_cr("uncommon_traps: %d",uncommonTrapStubCount);1421tty->print_cr("\nnmethod size distribution (non-zombie java)");1422tty->print_cr("-------------------------------------------------");14231424for(int i=0; i<bucketLimit; i++) {1425if(buckets[i] != 0) {1426tty->print("%d - %d bytes",i*bucketSize,(i+1)*bucketSize);1427tty->fill_to(40);1428tty->print_cr("%d",buckets[i]);1429}1430}14311432FREE_C_HEAP_ARRAY(int, buckets);1433print_memory_overhead();1434}14351436#endif // !PRODUCT14371438void CodeCache::print() {1439print_summary(tty);14401441#ifndef PRODUCT1442if (!Verbose) return;14431444CodeBlob_sizes live;1445CodeBlob_sizes dead;14461447FOR_ALL_ALLOCABLE_HEAPS(heap) {1448FOR_ALL_BLOBS(cb, *heap) {1449if (!cb->is_alive()) {1450dead.add(cb);1451} else {1452live.add(cb);1453}1454}1455}14561457tty->print_cr("CodeCache:");1458tty->print_cr("nmethod dependency checking time %fs", dependentCheckTime.seconds());14591460if (!live.is_empty()) {1461live.print("live");1462}1463if (!dead.is_empty()) {1464dead.print("dead");1465}14661467if (WizardMode) {1468// print the oop_map usage1469int code_size = 0;1470int number_of_blobs = 0;1471int number_of_oop_maps = 0;1472int map_size = 0;1473FOR_ALL_ALLOCABLE_HEAPS(heap) {1474FOR_ALL_BLOBS(cb, *heap) {1475if (cb->is_alive()) {1476number_of_blobs++;1477code_size += cb->code_size();1478ImmutableOopMapSet* set = cb->oop_maps();1479if (set != NULL) {1480number_of_oop_maps += set->count();1481map_size += set->nr_of_bytes();1482}1483}1484}1485}1486tty->print_cr("OopMaps");1487tty->print_cr(" #blobs = %d", number_of_blobs);1488tty->print_cr(" code size = %d", code_size);1489tty->print_cr(" #oop_maps = %d", number_of_oop_maps);1490tty->print_cr(" map size = %d", map_size);1491}14921493#endif // !PRODUCT1494}14951496void CodeCache::print_summary(outputStream* st, bool detailed) {1497int full_count = 0;1498FOR_ALL_HEAPS(heap_iterator) {1499CodeHeap* heap = (*heap_iterator);1500size_t total = (heap->high_boundary() - heap->low_boundary());1501if (_heaps->length() >= 1) {1502st->print("%s:", heap->name());1503} else {1504st->print("CodeCache:");1505}1506st->print_cr(" size=" SIZE_FORMAT "Kb used=" SIZE_FORMAT1507"Kb max_used=" SIZE_FORMAT "Kb free=" SIZE_FORMAT "Kb",1508total/K, (total - heap->unallocated_capacity())/K,1509heap->max_allocated_capacity()/K, heap->unallocated_capacity()/K);15101511if (detailed) {1512st->print_cr(" bounds [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT "]",1513p2i(heap->low_boundary()),1514p2i(heap->high()),1515p2i(heap->high_boundary()));15161517full_count += get_codemem_full_count(heap->code_blob_type());1518}1519}15201521if (detailed) {1522st->print_cr(" total_blobs=" UINT32_FORMAT " nmethods=" UINT32_FORMAT1523" adapters=" UINT32_FORMAT,1524blob_count(), nmethod_count(), adapter_count());1525st->print_cr(" compilation: %s", CompileBroker::should_compile_new_jobs() ?1526"enabled" : Arguments::mode() == Arguments::_int ?1527"disabled (interpreter mode)" :1528"disabled (not enough contiguous free space left)");1529st->print_cr(" stopped_count=%d, restarted_count=%d",1530CompileBroker::get_total_compiler_stopped_count(),1531CompileBroker::get_total_compiler_restarted_count());1532st->print_cr(" full_count=%d", full_count);1533}1534}15351536void CodeCache::print_codelist(outputStream* st) {1537MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);15381539CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);1540while (iter.next()) {1541CompiledMethod* cm = iter.method();1542ResourceMark rm;1543char* method_name = cm->method()->name_and_sig_as_C_string();1544st->print_cr("%d %d %d %s [" INTPTR_FORMAT ", " INTPTR_FORMAT " - " INTPTR_FORMAT "]",1545cm->compile_id(), cm->comp_level(), cm->get_state(),1546method_name,1547(intptr_t)cm->header_begin(), (intptr_t)cm->code_begin(), (intptr_t)cm->code_end());1548}1549}15501551void CodeCache::print_layout(outputStream* st) {1552MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);1553ResourceMark rm;1554print_summary(st, true);1555}15561557void CodeCache::log_state(outputStream* st) {1558st->print(" total_blobs='" UINT32_FORMAT "' nmethods='" UINT32_FORMAT "'"1559" adapters='" UINT32_FORMAT "' free_code_cache='" SIZE_FORMAT "'",1560blob_count(), nmethod_count(), adapter_count(),1561unallocated_capacity());1562}15631564#ifdef LINUX1565void CodeCache::write_perf_map() {1566MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);15671568// Perf expects to find the map file at /tmp/perf-<pid>.map.1569char fname[32];1570jio_snprintf(fname, sizeof(fname), "/tmp/perf-%d.map", os::current_process_id());15711572fileStream fs(fname, "w");1573if (!fs.is_open()) {1574log_warning(codecache)("Failed to create %s for perf map", fname);1575return;1576}15771578AllCodeBlobsIterator iter(AllCodeBlobsIterator::only_alive_and_not_unloading);1579while (iter.next()) {1580CodeBlob *cb = iter.method();1581ResourceMark rm;1582const char* method_name =1583cb->is_compiled() ? cb->as_compiled_method()->method()->external_name()1584: cb->name();1585fs.print_cr(INTPTR_FORMAT " " INTPTR_FORMAT " %s",1586(intptr_t)cb->code_begin(), (intptr_t)cb->code_size(),1587method_name);1588}1589}1590#endif // LINUX15911592//---< BEGIN >--- CodeHeap State Analytics.15931594void CodeCache::aggregate(outputStream *out, size_t granularity) {1595FOR_ALL_ALLOCABLE_HEAPS(heap) {1596CodeHeapState::aggregate(out, (*heap), granularity);1597}1598}15991600void CodeCache::discard(outputStream *out) {1601FOR_ALL_ALLOCABLE_HEAPS(heap) {1602CodeHeapState::discard(out, (*heap));1603}1604}16051606void CodeCache::print_usedSpace(outputStream *out) {1607FOR_ALL_ALLOCABLE_HEAPS(heap) {1608CodeHeapState::print_usedSpace(out, (*heap));1609}1610}16111612void CodeCache::print_freeSpace(outputStream *out) {1613FOR_ALL_ALLOCABLE_HEAPS(heap) {1614CodeHeapState::print_freeSpace(out, (*heap));1615}1616}16171618void CodeCache::print_count(outputStream *out) {1619FOR_ALL_ALLOCABLE_HEAPS(heap) {1620CodeHeapState::print_count(out, (*heap));1621}1622}16231624void CodeCache::print_space(outputStream *out) {1625FOR_ALL_ALLOCABLE_HEAPS(heap) {1626CodeHeapState::print_space(out, (*heap));1627}1628}16291630void CodeCache::print_age(outputStream *out) {1631FOR_ALL_ALLOCABLE_HEAPS(heap) {1632CodeHeapState::print_age(out, (*heap));1633}1634}16351636void CodeCache::print_names(outputStream *out) {1637FOR_ALL_ALLOCABLE_HEAPS(heap) {1638CodeHeapState::print_names(out, (*heap));1639}1640}1641//---< END >--- CodeHeap State Analytics.164216431644