/* * Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. *
*/
// Helper class for printing in CodeCache class CodeBlob_sizes { private: int count; int total_size; int header_size; int code_size; int stub_size; int relocation_size; int scopes_oop_size; int scopes_metadata_size; int scopes_data_size; int scopes_pcs_size;
// Iterate over all CodeHeaps #define FOR_ALL_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _heaps->begin(); heap != _heaps->end(); ++heap) #define FOR_ALL_NMETHOD_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _nmethod_heaps->begin(); heap != _nmethod_heaps->end(); ++heap) #define FOR_ALL_ALLOCABLE_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _allocable_heaps->begin(); heap != _allocable_heaps->end(); ++heap)
// Iterate over all CodeBlobs (cb) on the given CodeHeap #define FOR_ALL_BLOBS(cb, heap) for (CodeBlob* cb = first_blob(heap); cb != NULL; cb = next_blob(heap, cb))
if (total_size > cache_size) { // Some code heap sizes were explicitly set: total_size must be <= cache_size
message.append(" is greater than ReservedCodeCacheSize (" SIZE_FORMAT "K).", cache_size/K);
vm_exit_during_initialization(error, message);
} elseif (all_set && total_size != cache_size) { // All code heap sizes were explicitly set: total_size must equal cache_size
message.append(" is not equal to ReservedCodeCacheSize (" SIZE_FORMAT "K).", cache_size/K);
vm_exit_during_initialization(error, message);
}
}
// Determine size of compiler buffers
size_t code_buffers_size = 0; #ifdef COMPILER1 // C1 temporary code buffers (see Compiler::init_buffer_blob()) constint c1_count = CompilationPolicy::c1_count();
code_buffers_size += c1_count * Compiler::code_buffer_size(); #endif #ifdef COMPILER2 // C2 scratch buffers (see Compile::init_scratch_buffer_blob()) constint c2_count = CompilationPolicy::c2_count(); // Initial size of constant table (this may be increased if a compiled method needs more space)
code_buffers_size += c2_count * C2Compiler::initial_code_buffer_size(); #endif
// Increase default non_nmethod_size to account for compiler buffers if (!non_nmethod_set) {
non_nmethod_size += code_buffers_size;
} // Calculate default CodeHeap sizes if not set by user if (!non_nmethod_set && !profiled_set && !non_profiled_set) { // Check if we have enough space for the non-nmethod code heap if (cache_size > non_nmethod_size) { // Use the default value for non_nmethod_size and one half of the // remaining size for non-profiled and one half for profiled methods
size_t remaining_size = cache_size - non_nmethod_size;
profiled_size = remaining_size / 2;
non_profiled_size = remaining_size - profiled_size;
} else { // Use all space for the non-nmethod heap and set other heaps to minimal size
non_nmethod_size = cache_size - 2 * min_size;
profiled_size = min_size;
non_profiled_size = min_size;
}
} elseif (!non_nmethod_set || !profiled_set || !non_profiled_set) { // The user explicitly set some code heap sizes. Increase or decrease the (default) // sizes of the other code heaps accordingly. First adapt non-profiled and profiled // code heap sizes and then only change non-nmethod code heap size if still necessary.
intx diff_size = cache_size - (non_nmethod_size + profiled_size + non_profiled_size); if (non_profiled_set) { if (!profiled_set) { // Adapt size of profiled code heap if (diff_size < 0 && ((intx)profiled_size + diff_size) <= 0) { // Not enough space available, set to minimum size
diff_size += profiled_size - min_size;
profiled_size = min_size;
} else {
profiled_size += diff_size;
diff_size = 0;
}
}
} elseif (profiled_set) { // Adapt size of non-profiled code heap if (diff_size < 0 && ((intx)non_profiled_size + diff_size) <= 0) { // Not enough space available, set to minimum size
diff_size += non_profiled_size - min_size;
non_profiled_size = min_size;
} else {
non_profiled_size += diff_size;
diff_size = 0;
}
} elseif (non_nmethod_set) { // Distribute remaining size between profiled and non-profiled code heaps
diff_size = cache_size - non_nmethod_size;
profiled_size = diff_size / 2;
non_profiled_size = diff_size - profiled_size;
diff_size = 0;
} if (diff_size != 0) { // Use non-nmethod code heap for remaining space requirements
assert(!non_nmethod_set && ((intx)non_nmethod_size + diff_size) > 0, "sanity");
non_nmethod_size += diff_size;
}
}
// We do not need the profiled CodeHeap, use all space for the non-profiled CodeHeap if (!heap_available(CodeBlobType::MethodProfiled)) {
non_profiled_size += profiled_size;
profiled_size = 0;
} // We do not need the non-profiled CodeHeap, use all space for the non-nmethod CodeHeap if (!heap_available(CodeBlobType::MethodNonProfiled)) {
non_nmethod_size += non_profiled_size;
non_profiled_size = 0;
} // Make sure we have enough space for VM internal code
uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3); if (non_nmethod_size < min_code_cache_size) {
vm_exit_during_initialization(err_msg( "Not enough space in non-nmethod code heap to run VM: " SIZE_FORMAT "K < " SIZE_FORMAT "K",
non_nmethod_size/K, min_code_cache_size/K));
}
// If large page support is enabled, align code heaps according to large // page size to make sure that code cache is covered by large pages. const size_t alignment = MAX2(page_size(false, 8), (size_t) os::vm_allocation_granularity());
non_nmethod_size = align_up(non_nmethod_size, alignment);
profiled_size = align_down(profiled_size, alignment);
non_profiled_size = align_down(non_profiled_size, alignment);
// Reserve one continuous chunk of memory for CodeHeaps and split it into // parts for the individual heaps. The memory layout looks like this: // ---------- high ----------- // Non-profiled nmethods // Non-nmethods // Profiled nmethods // ---------- low ------------
ReservedCodeSpace rs = reserve_heap_memory(cache_size);
ReservedSpace profiled_space = rs.first_part(profiled_size);
ReservedSpace rest = rs.last_part(profiled_size);
ReservedSpace non_method_space = rest.first_part(non_nmethod_size);
ReservedSpace non_profiled_space = rest.last_part(non_nmethod_size);
size_t CodeCache::page_size(bool aligned, size_t min_pages) { if (os::can_execute_large_page_memory()) { if (InitialCodeCacheSize < ReservedCodeCacheSize) { // Make sure that the page size allows for an incremental commit of the reserved space
min_pages = MAX2(min_pages, (size_t)8);
} return aligned ? os::page_size_for_region_aligned(ReservedCodeCacheSize, min_pages) :
os::page_size_for_region_unaligned(ReservedCodeCacheSize, min_pages);
} else { return os::vm_page_size();
}
}
ReservedCodeSpace CodeCache::reserve_heap_memory(size_t size) { // Align and reserve space for code cache const size_t rs_ps = page_size(); const size_t rs_align = MAX2(rs_ps, (size_t) os::vm_allocation_granularity()); const size_t rs_size = align_up(size, rs_align);
ReservedCodeSpace rs(rs_size, rs_align, rs_ps); if (!rs.is_reserved()) {
vm_exit_during_initialization(err_msg("Could not reserve enough space for code cache (" SIZE_FORMAT "K)",
rs_size/K));
}
// Heaps available for allocation bool CodeCache::heap_available(CodeBlobType code_blob_type) { if (!SegmentedCodeCache) { // No segmentation: use a single code heap return (code_blob_type == CodeBlobType::All);
} elseif (CompilerConfig::is_interpreter_only()) { // Interpreter only: we don't need any method code heaps return (code_blob_type == CodeBlobType::NonNMethod);
} elseif (CompilerConfig::is_c1_profiling()) { // Tiered compilation: use all code heaps return (code_blob_type < CodeBlobType::All);
} else { // No TieredCompilation: we only need the non-nmethod and non-profiled code heap return (code_blob_type == CodeBlobType::NonNMethod) ||
(code_blob_type == CodeBlobType::MethodNonProfiled);
}
}
constchar* CodeCache::get_code_heap_flag_name(CodeBlobType code_blob_type) { switch(code_blob_type) { case CodeBlobType::NonNMethod: return"NonNMethodCodeHeapSize"; break; case CodeBlobType::MethodNonProfiled: return"NonProfiledCodeHeapSize"; break; case CodeBlobType::MethodProfiled: return"ProfiledCodeHeapSize"; break; default:
ShouldNotReachHere(); return NULL;
}
}
CodeBlobType type = heap->code_blob_type(); if (code_blob_type_accepts_compiled(type)) {
_compiled_heaps->insert_sorted<code_heap_compare>(heap);
} if (code_blob_type_accepts_nmethod(type)) {
_nmethod_heaps->insert_sorted<code_heap_compare>(heap);
} if (code_blob_type_accepts_allocable(type)) {
_allocable_heaps->insert_sorted<code_heap_compare>(heap);
}
}
void CodeCache::add_heap(ReservedSpace rs, constchar* name, CodeBlobType code_blob_type) { // Check if heap is needed if (!heap_available(code_blob_type)) { return;
}
// Create CodeHeap
CodeHeap* heap = new CodeHeap(name, code_blob_type);
add_heap(heap);
// Reserve Space
size_t size_initial = MIN2((size_t)InitialCodeCacheSize, rs.size());
size_initial = align_up(size_initial, os::vm_page_size()); if (!heap->reserve(rs, size_initial, CodeCacheSegmentSize)) {
vm_exit_during_initialization(err_msg("Could not reserve enough space in %s (" SIZE_FORMAT "K)",
heap->name(), size_initial/K));
}
// Register the CodeHeap
MemoryService::add_code_heap_memory_pool(heap, name);
}
/** * Do not seize the CodeCache lock here--if the caller has not * already done so, we are going to lose bigtime, since the code * cache will contain a garbage CodeBlob until the caller can * run the constructor for the CodeBlob subclass he is busy * instantiating.
*/
CodeBlob* CodeCache::allocate(int size, CodeBlobType code_blob_type, bool handle_alloc_failure, CodeBlobType orig_code_blob_type) {
assert_locked_or_safepoint(CodeCache_lock);
assert(size > 0, "Code cache allocation request must be > 0 but is %d", size); if (size <= 0) { return NULL;
}
CodeBlob* cb = NULL;
// Get CodeHeap for the given CodeBlobType
CodeHeap* heap = get_code_heap(code_blob_type);
assert(heap != NULL, "heap is null");
while (true) {
cb = (CodeBlob*)heap->allocate(size); if (cb != NULL) break; if (!heap->expand_by(CodeCacheExpansionSize)) { // Save original type for error reporting if (orig_code_blob_type == CodeBlobType::All) {
orig_code_blob_type = code_blob_type;
} // Expansion failed if (SegmentedCodeCache) { // Fallback solution: Try to store code in another code heap. // NonNMethod -> MethodNonProfiled -> MethodProfiled (-> MethodNonProfiled)
CodeBlobType type = code_blob_type; switch (type) { case CodeBlobType::NonNMethod:
type = CodeBlobType::MethodNonProfiled; break; case CodeBlobType::MethodNonProfiled:
type = CodeBlobType::MethodProfiled; break; case CodeBlobType::MethodProfiled: // Avoid loop if we already tried that code heap if (type == orig_code_blob_type) {
type = CodeBlobType::MethodNonProfiled;
} break; default: break;
} if (type != code_blob_type && type != orig_code_blob_type && heap_available(type)) { if (PrintCodeCacheExtension) {
tty->print_cr("Extension of %s failed. Trying to allocate in %s.",
heap->name(), get_code_heap(type)->name());
} return allocate(size, type, handle_alloc_failure, orig_code_blob_type);
}
} if (handle_alloc_failure) {
MutexUnlocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
CompileBroker::handle_full_code_cache(orig_code_blob_type);
} return NULL;
} if (PrintCodeCacheExtension) {
ResourceMark rm; if (_nmethod_heaps->length() >= 1) {
tty->print("%s", heap->name());
} else {
tty->print("CodeCache");
}
tty->print_cr(" extended to [" INTPTR_FORMAT ", " INTPTR_FORMAT "] (" SSIZE_FORMAT " bytes)",
(intptr_t)heap->low_boundary(), (intptr_t)heap->high(),
(address)heap->high() - (address)heap->low_boundary());
}
}
print_trace("allocation", cb, size); return cb;
}
void CodeCache::free_unused_tail(CodeBlob* cb, size_t used) {
assert_locked_or_safepoint(CodeCache_lock);
guarantee(cb->is_buffer_blob() && strncmp("Interpreter", cb->name(), 11) == 0, "Only possible for interpreter!");
print_trace("free_unused_tail", cb);
// We also have to account for the extra space (i.e. header) used by the CodeBlob // which provides the memory (see BufferBlob::create() in codeBlob.cpp).
used += CodeBlob::align_code_offset(cb->header_size());
// Get heap for given CodeBlob and deallocate its unused tail
get_code_heap(cb)->deallocate_tail(cb, used); // Adjust the sizes of the CodeBlob
cb->adjust_size(used);
}
void CodeCache::commit(CodeBlob* cb) { // this is called by nmethod::nmethod, which must already own CodeCache_lock
assert_locked_or_safepoint(CodeCache_lock);
CodeHeap* heap = get_code_heap(cb); if (cb->is_nmethod()) {
heap->set_nmethod_count(heap->nmethod_count() + 1); if (((nmethod *)cb)->has_dependencies()) {
_number_of_nmethods_with_dependencies++;
}
} if (cb->is_adapter_blob()) {
heap->set_adapter_count(heap->adapter_count() + 1);
}
// flush the hardware I-cache
ICache::invalidate_range(cb->content_begin(), cb->content_size());
}
bool CodeCache::contains(void *p) { // S390 uses contains() in current_frame(), which is used before // code cache initialization if NativeMemoryTracking=detail is set.
S390_ONLY(if (_heaps == NULL) returnfalse;) // It should be ok to call contains without holding a lock.
FOR_ALL_HEAPS(heap) { if ((*heap)->contains(p)) { returntrue;
}
} returnfalse;
}
// This method is safe to call without holding the CodeCache_lock. It only depends on the _segmap to contain // valid indices, which it will always do, as long as the CodeBlob is not in the process of being recycled.
CodeBlob* CodeCache::find_blob(void* start) { // NMT can walk the stack before code cache is created if (_heaps != NULL) {
CodeHeap* heap = get_code_heap_containing(start); if (heap != NULL) { return heap->find_blob(start);
}
} return NULL;
}
nmethod* CodeCache::find_nmethod(void* start) {
CodeBlob* cb = find_blob(start);
assert(cb->is_nmethod(), "did not find an nmethod"); return (nmethod*)cb;
}
int CodeCache::alignment_unit() { return (int)_heaps->first()->alignment_unit();
}
int CodeCache::alignment_offset() { return (int)_heaps->first()->alignment_offset();
}
// Calculate the number of GCs after which an nmethod is expected to have been // used in order to not be classed as cold. void CodeCache::update_cold_gc_count() { if (!MethodFlushing || !UseCodeCacheFlushing || NmethodSweepActivity == 0) { // No aging return;
}
if (last_time == 0.0) { // The first GC doesn't have enough information to make good // decisions, so just keep everything afloat
log_info(codecache)("Unknown code cache pressure; don't age code"); return;
}
if (gc_interval <= 0.0 || last_used >= used) { // Dodge corner cases where there is no pressure or negative pressure // on the code cache. Just don't unload when this happens.
_cold_gc_count = INT_MAX;
log_info(codecache)("No code cache pressure; don't age code"); return;
}
size_t aggressive_sweeping_free_threshold = StartAggressiveSweepingAt / 100.0 * max; if (free < aggressive_sweeping_free_threshold) { // We are already in the red zone; be very aggressive to avoid disaster // But not more aggressive than 2. This ensures that an nmethod must // have been unused at least between two GCs to be considered cold still.
_cold_gc_count = 2;
log_info(codecache)("Code cache critically low; use aggressive aging"); return;
}
// The code cache has an expected time for cold nmethods to "time out" // when they have not been used. The time for nmethods to time out // depends on how long we expect we can keep allocating code until // aggressive sweeping starts, based on sampled allocation rates. double average_gc_interval = _unloading_gc_intervals.avg(); double average_allocation_rate = _unloading_allocation_rates.avg(); double time_to_aggressive = ((double)(free - aggressive_sweeping_free_threshold)) / average_allocation_rate; double cold_timeout = time_to_aggressive / NmethodSweepActivity;
// Convert time to GC cycles, and crop at INT_MAX. The reason for // that is that the _cold_gc_count will be added to an epoch number // and that addition must not overflow, or we can crash the VM. // But not more aggressive than 2. This ensures that an nmethod must // have been unused at least between two GCs to be considered cold still.
_cold_gc_count = MAX2(MIN2((uint64_t)(cold_timeout / average_gc_interval), (uint64_t)INT_MAX), (uint64_t)2);
void CodeCache::gc_on_allocation() { if (!is_init_completed()) { // Let's not heuristically trigger GCs before the JVM is ready for GCs, no matter what return;
}
size_t free = unallocated_capacity();
size_t max = max_capacity();
size_t used = max - free; double free_ratio = double(free) / double(max); if (free_ratio <= StartAggressiveSweepingAt / 100.0) { // In case the GC is concurrent, we make sure only one thread requests the GC. if (Atomic::cmpxchg(&_unloading_threshold_gc_requested, false, true) == false) {
log_info(codecache)("Triggering aggressive GC due to having only %.3f%% free memory", free_ratio * 100.0);
Universe::heap()->collect(GCCause::_codecache_GC_aggressive);
} return;
}
size_t last_used = _last_unloading_used; if (last_used >= used) { // No increase since last GC; no need to sweep yet return;
}
size_t allocated_since_last = used - last_used; double allocated_since_last_ratio = double(allocated_since_last) / double(max); double threshold = SweeperThreshold / 100.0; double used_ratio = double(used) / double(max); double last_used_ratio = double(last_used) / double(max); if (used_ratio > threshold) { // After threshold is reached, scale it by free_ratio so that more aggressive // GC is triggered as we approach code cache exhaustion
threshold *= free_ratio;
} // If code cache has been allocated without any GC at all, let's make sure // it is eventually invoked to avoid trouble. if (allocated_since_last_ratio > threshold) { // In case the GC is concurrent, we make sure only one thread requests the GC. if (Atomic::cmpxchg(&_unloading_threshold_gc_requested, false, true) == false) {
log_info(codecache)("Triggering threshold (%.3f%%) GC due to allocating %.3f%% since last unloading (%.3f%% used -> %.3f%% used)",
threshold * 100.0, allocated_since_last_ratio * 100.0, last_used_ratio * 100.0, used_ratio * 100.0);
Universe::heap()->collect(GCCause::_codecache_GC_threshold);
}
}
}
// We initialize the _gc_epoch to 2, because previous_completed_gc_marking_cycle // subtracts the value by 2, and the type is unsigned. We don't want underflow. // // Odd values mean that marking is in progress, and even values mean that no // marking is currently active.
uint64_t CodeCache::_gc_epoch = 2;
// How many GCs after an nmethod has not been used, do we consider it cold?
uint64_t CodeCache::_cold_gc_count = INT_MAX;
void CodeCache::on_gc_marking_cycle_finish() {
assert(is_gc_marking_cycle_active(), "Marking cycle started before last one finished");
++_gc_epoch;
update_cold_gc_count();
}
void CodeCache::verify_icholder_relocations() { #ifdef ASSERT // make sure that we aren't leaking icholders int count = 0;
FOR_ALL_HEAPS(heap) {
FOR_ALL_BLOBS(cb, *heap) {
CompiledMethod *nm = cb->as_compiled_method_or_null(); if (nm != NULL) {
count += nm->verify_icholder_relocations();
}
}
}
assert(count + InlineCacheBuffer::pending_icholder_count() + CompiledICHolder::live_not_claimed_count() ==
CompiledICHolder::live_count(), "must agree"); #endif
}
// Defer freeing of concurrently cleaned ExceptionCache entries until // after a global handshake operation. void CodeCache::release_exception_cache(ExceptionCache* entry) { if (SafepointSynchronize::is_at_safepoint()) { delete entry;
} else { for (;;) {
ExceptionCache* purge_list_head = Atomic::load(&_exception_cache_purge_list);
entry->set_purge_list_next(purge_list_head); if (Atomic::cmpxchg(&_exception_cache_purge_list, purge_list_head, entry) == purge_list_head) { break;
}
}
}
}
// Delete exception caches that have been concurrently unlinked, // followed by a global handshake operation. void CodeCache::purge_exception_caches() {
ExceptionCache* curr = _exception_cache_purge_list; while (curr != NULL) {
ExceptionCache* next = curr->purge_list_next(); delete curr;
curr = next;
}
_exception_cache_purge_list = NULL;
}
// Register an is_unloading nmethod to be flushed after unlinking void CodeCache::register_unlinked(nmethod* nm) {
assert(nm->unlinked_next() == NULL, "Only register for unloading once"); for (;;) { // Only need acquire when reading the head, when the next // pointer is walked, which it is not here.
nmethod* head = Atomic::load(&_unlinked_head);
nmethod* next = head != NULL ? head : nm; // Self looped means end of list
nm->set_unlinked_next(next); if (Atomic::cmpxchg(&_unlinked_head, head, nm) == head) { break;
}
}
}
// Flush all the nmethods the GC unlinked void CodeCache::flush_unlinked_nmethods() {
nmethod* nm = _unlinked_head;
_unlinked_head = NULL;
size_t freed_memory = 0; while (nm != NULL) {
nmethod* next = nm->unlinked_next();
freed_memory += nm->total_size();
nm->flush(); if (next == nm) { // Self looped means end of list break;
}
nm = next;
}
// Try to start the compiler again if we freed any memory if (!CompileBroker::should_compile_new_jobs() && freed_memory != 0) {
CompileBroker::set_should_compile_new_jobs(CompileBroker::run_compilation);
log_info(codecache)("Restarting compiler");
EventJITRestart event;
event.set_freedMemory(freed_memory);
event.set_codeCacheMaxCapacity(CodeCache::max_capacity());
event.commit();
}
}
void CodeCache::increment_unloading_cycle() { // 2-bit value (see IsUnloadingState in nmethod.cpp for details) // 0 is reserved for new methods.
_unloading_cycle = (_unloading_cycle + 1) % 4; if (_unloading_cycle == 0) {
_unloading_cycle = 1;
}
}
size_t CodeCache::max_distance_to_non_nmethod() { if (!SegmentedCodeCache) { return ReservedCodeCacheSize;
} else {
CodeHeap* blob = get_code_heap(CodeBlobType::NonNMethod); // the max distance is minimized by placing the NonNMethod segment // in between MethodProfiled and MethodNonProfiled segments
size_t dist1 = (size_t)blob->high() - (size_t)_low_bound;
size_t dist2 = (size_t)_high_bound - (size_t)blob->low(); return dist1 > dist2 ? dist1 : dist2;
}
}
// Returns the reverse free ratio. E.g., if 25% (1/4) of the code cache // is free, reverse_free_ratio() returns 4. // Since code heap for each type of code blobs falls forward to the next // type of code heap, return the reverse free ratio for the entire // code cache. double CodeCache::reverse_free_ratio() { double unallocated = MAX2((double)unallocated_capacity(), 1.0); // Avoid division by 0; double max = (double)max_capacity(); double result = max / unallocated;
assert (max >= unallocated, "Must be");
assert (result >= 1.0, "reverse_free_ratio must be at least 1. It is %f", result); return result;
}
void CodeCache::initialize() {
assert(CodeCacheSegmentSize >= (uintx)CodeEntryAlignment, "CodeCacheSegmentSize must be large enough to align entry points"); #ifdef COMPILER2
assert(CodeCacheSegmentSize >= (uintx)OptoLoopAlignment, "CodeCacheSegmentSize must be large enough to align inner loops"); #endif
assert(CodeCacheSegmentSize >= sizeof(jdouble), "CodeCacheSegmentSize must be large enough to align constants"); // This was originally just a check of the alignment, causing failure, instead, round // the code cache to the page size. In particular, Solaris is moving to a larger // default page size.
CodeCacheExpansionSize = align_up(CodeCacheExpansionSize, os::vm_page_size());
if (SegmentedCodeCache) { // Use multiple code heaps
initialize_heaps();
} else { // Use a single code heap
FLAG_SET_ERGO(NonNMethodCodeHeapSize, 0);
FLAG_SET_ERGO(ProfiledCodeHeapSize, 0);
FLAG_SET_ERGO(NonProfiledCodeHeapSize, 0);
ReservedCodeSpace rs = reserve_heap_memory(ReservedCodeCacheSize);
add_heap(rs, "CodeCache", CodeBlobType::All);
}
// Initialize ICache flush mechanism // This service is needed for os::register_code_area
icache_init();
// Give OS a chance to register generated code area. // This is used on Windows 64 bit platforms to register // Structured Exception Handlers for our generated code.
os::register_code_area((char*)low_bound(), (char*)high_bound());
}
// Only used by whitebox API void CodeCache::cleanup_inline_caches_whitebox() {
assert_locked_or_safepoint(CodeCache_lock);
NMethodIterator iter(NMethodIterator::only_not_unloading); while(iter.next()) {
iter.method()->cleanup_inline_caches_whitebox();
}
}
// Keeps track of time spent for checking dependencies
NOT_PRODUCT(static elapsedTimer dependentCheckTime;)
int CodeCache::mark_for_deoptimization(KlassDepChange& changes) {
MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); int number_of_marked_CodeBlobs = 0;
// search the hierarchy looking for nmethods which are affected by the loading of this class
// then search the interfaces this class implements looking for nmethods // which might be dependent of the fact that an interface only had one // implementor. // nmethod::check_all_dependencies works only correctly, if no safepoint // can happen
NoSafepointVerifier nsv; for (DepChange::ContextStream str(changes, nsv); str.next(); ) {
Klass* d = str.klass();
number_of_marked_CodeBlobs += InstanceKlass::cast(d)->mark_dependent_nmethods(changes);
}
#ifndef PRODUCT if (VerifyDependencies) { // Object pointers are used as unique identifiers for dependency arguments. This // is only possible if no safepoint, i.e., GC occurs during the verification code.
dependentCheckTime.start();
nmethod::check_all_dependencies(changes);
dependentCheckTime.stop();
} #endif
#if INCLUDE_JVMTI // RedefineClasses support for saving nmethods that are dependent on "old" methods. // We don't really expect this table to grow very large. If it does, it can become a hashtable. static GrowableArray<CompiledMethod*>* old_compiled_method_table = NULL;
staticvoid add_to_old_table(CompiledMethod* c) { if (old_compiled_method_table == NULL) {
old_compiled_method_table = new (mtCode) GrowableArray<CompiledMethod*>(100, mtCode);
}
old_compiled_method_table->push(c);
}
// Remove this method when flushed. void CodeCache::unregister_old_nmethod(CompiledMethod* c) {
assert_lock_strong(CodeCache_lock); if (old_compiled_method_table != NULL) { int index = old_compiled_method_table->find(c); if (index != -1) {
old_compiled_method_table->delete_at(index);
}
}
}
void CodeCache::old_nmethods_do(MetadataClosure* f) { // Walk old method table and mark those on stack. int length = 0; if (old_compiled_method_table != NULL) {
length = old_compiled_method_table->length(); for (int i = 0; i < length; i++) { // Walk all methods saved on the last pass. Concurrent class unloading may // also be looking at this method's metadata, so don't delete it yet if // it is marked as unloaded.
old_compiled_method_table->at(i)->metadata_do(f);
}
}
log_debug(redefine, class, nmethod)("Walked %d nmethods for mark_on_stack", length);
}
// Walk compiled methods and mark dependent methods for deoptimization. int CodeCache::mark_dependents_for_evol_deoptimization() {
assert(SafepointSynchronize::is_at_safepoint(), "Can only do this at a safepoint!"); // Each redefinition creates a new set of nmethods that have references to "old" Methods // So delete old method table and create a new one.
reset_old_method_table();
int number_of_marked_CodeBlobs = 0;
CompiledMethodIterator iter(CompiledMethodIterator::all_blobs); while(iter.next()) {
CompiledMethod* nm = iter.method(); // Walk all alive nmethods to check for old Methods. // This includes methods whose inline caches point to old methods, so // inline cache clearing is unnecessary. if (nm->has_evol_metadata()) {
nm->mark_for_deoptimization();
add_to_old_table(nm);
number_of_marked_CodeBlobs++;
}
}
// return total count of nmethods marked for deoptimization, if zero the caller // can skip deoptimization return number_of_marked_CodeBlobs;
}
void CodeCache::mark_all_nmethods_for_evol_deoptimization() {
assert(SafepointSynchronize::is_at_safepoint(), "Can only do this at a safepoint!");
CompiledMethodIterator iter(CompiledMethodIterator::all_blobs); while(iter.next()) {
CompiledMethod* nm = iter.method(); if (!nm->method()->is_method_handle_intrinsic()) { if (nm->can_be_deoptimized()) {
nm->mark_for_deoptimization();
} if (nm->has_evol_metadata()) {
add_to_old_table(nm);
}
}
}
}
// Flushes compiled methods dependent on redefined classes, that have already been // marked for deoptimization. void CodeCache::flush_evol_dependents() {
assert(SafepointSynchronize::is_at_safepoint(), "Can only do this at a safepoint!");
// CodeCache can only be updated by a thread_in_VM and they will all be // stopped during the safepoint so CodeCache will be safe to update without // holding the CodeCache_lock.
// At least one nmethod has been marked for deoptimization
if (number_of_nmethods_with_dependencies() == 0) return;
int marked = 0; if (dependee->is_linked()) { // Class initialization state change.
KlassInitDepChange changes(dependee);
marked = mark_for_deoptimization(changes);
} else { // New class is loaded.
NewKlassDepChange changes(dependee);
marked = mark_for_deoptimization(changes);
}
if (marked > 0) { // At least one nmethod has been marked for deoptimization
Deoptimization::deoptimize_all_marked();
}
}
// Flushes compiled methods dependent on dependee void CodeCache::flush_dependents_on_method(const methodHandle& m_h) { // --- Compile_lock is not held. However we are at a safepoint.
assert_locked_or_safepoint(Compile_lock);
// Compute the dependent nmethods if (mark_for_deoptimization(m_h()) > 0) {
Deoptimization::deoptimize_all_marked();
}
}
// A CodeHeap is full. Print out warning and report event.
PRAGMA_DIAG_PUSH
PRAGMA_FORMAT_NONLITERAL_IGNORED void CodeCache::report_codemem_full(CodeBlobType code_blob_type, bool print) { // Get nmethod heap for the given CodeBlobType and build CodeCacheFull event
CodeHeap* heap = get_code_heap(code_blob_type);
assert(heap != NULL, "heap is null");
int full_count = heap->report_full();
if ((full_count == 1) || print) { // Not yet reported for this heap, report if (SegmentedCodeCache) {
ResourceMark rm;
stringStream msg1_stream, msg2_stream;
msg1_stream.print("%s is full. Compiler has been disabled.",
get_code_heap_name(code_blob_type));
msg2_stream.print("Try increasing the code heap size using -XX:%s=",
get_code_heap_flag_name(code_blob_type)); constchar *msg1 = msg1_stream.as_string(); constchar *msg2 = msg2_stream.as_string();
log_warning(codecache)("%s", msg1);
log_warning(codecache)("%s", msg2);
warning("%s", msg1);
warning("%s", msg2);
} else { constchar *msg1 = "CodeCache is full. Compiler has been disabled."; constchar *msg2 = "Try increasing the code cache size using -XX:ReservedCodeCacheSize=";
log_warning(codecache)("%s", msg1);
log_warning(codecache)("%s", msg2);
warning("%s", msg1);
warning("%s", msg2);
}
stringStream s; // Dump code cache into a buffer before locking the tty.
{
MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
print_summary(&s);
}
{
ttyLocker ttyl;
tty->print("%s", s.freeze());
}
if (full_count == 1) { if (PrintCodeHeapAnalytics) {
CompileBroker::print_heapinfo(tty, "all", 4096); // details, may be a lot!
}
}
}
void CodeCache::print_memory_overhead() {
size_t wasted_bytes = 0;
FOR_ALL_ALLOCABLE_HEAPS(heap) {
CodeHeap* curr_heap = *heap; for (CodeBlob* cb = (CodeBlob*)curr_heap->first(); cb != NULL; cb = (CodeBlob*)curr_heap->next(cb)) {
HeapBlock* heap_block = ((HeapBlock*)cb) - 1;
wasted_bytes += heap_block->length() * CodeCacheSegmentSize - cb->size();
}
} // Print bytes that are allocated in the freelist
ttyLocker ttl;
tty->print_cr("Number of elements in freelist: " SSIZE_FORMAT, freelists_length());
tty->print_cr("Allocated in freelist: " SSIZE_FORMAT "kB", bytes_allocated_in_freelists()/K);
tty->print_cr("Unused bytes in CodeBlobs: " SSIZE_FORMAT "kB", (wasted_bytes/K));
tty->print_cr("Segment map size: " SSIZE_FORMAT "kB", allocated_segments()/K); // 1 byte per segment
}
//------------------------------------------------------------------------------------------------ // Non-product version
#ifndef PRODUCT
void CodeCache::print_trace(constchar* event, CodeBlob* cb, int size) { if (PrintCodeCache2) { // Need to add a new flag
ResourceMark rm; if (size == 0) size = cb->size();
tty->print_cr("CodeCache %s: addr: " INTPTR_FORMAT ", size: 0x%x", event, p2i(cb), size);
}
}
void CodeCache::print_internals() { int nmethodCount = 0; int runtimeStubCount = 0; int adapterCount = 0; int deoptimizationStubCount = 0; int uncommonTrapStubCount = 0; int bufferBlobCount = 0; int total = 0; int nmethodNotEntrant = 0; int nmethodJava = 0; int nmethodNative = 0; int max_nm_size = 0;
ResourceMark rm;
int i = 0;
FOR_ALL_ALLOCABLE_HEAPS(heap) { if ((_nmethod_heaps->length() >= 1) && Verbose) {
tty->print_cr("-- %s --", (*heap)->name());
}
FOR_ALL_BLOBS(cb, *heap) {
total++; if (cb->is_nmethod()) {
nmethod* nm = (nmethod*)cb;
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung ist noch experimentell.