1 /*
   2  * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "code/codeBlob.hpp"
  26 #include "code/codeCache.hpp"
  27 #include "code/codeHeapState.hpp"
  28 #include "code/compiledIC.hpp"
  29 #include "code/dependencies.hpp"
  30 #include "code/dependencyContext.hpp"
  31 #include "code/nmethod.hpp"
  32 #include "code/pcDesc.hpp"
  33 #include "compiler/compilationPolicy.hpp"
  34 #include "compiler/compileBroker.hpp"
  35 #include "compiler/compilerDefinitions.inline.hpp"
  36 #include "compiler/oopMap.hpp"
  37 #include "gc/shared/barrierSetNMethod.hpp"
  38 #include "gc/shared/classUnloadingContext.hpp"
  39 #include "gc/shared/collectedHeap.hpp"
  40 #include "jfr/jfrEvents.hpp"
  41 #include "jvm_io.h"
  42 #include "logging/log.hpp"
  43 #include "logging/logStream.hpp"
  44 #include "memory/allocation.inline.hpp"
  45 #include "memory/iterator.hpp"
  46 #include "memory/memoryReserver.hpp"
  47 #include "memory/resourceArea.hpp"
  48 #include "memory/universe.hpp"
  49 #include "oops/method.inline.hpp"
  50 #include "oops/objArrayOop.hpp"
  51 #include "oops/oop.inline.hpp"
  52 #include "oops/verifyOopClosure.hpp"
  53 #include "runtime/arguments.hpp"
  54 #include "runtime/atomicAccess.hpp"
  55 #include "runtime/deoptimization.hpp"
  56 #include "runtime/globals_extension.hpp"
  57 #include "runtime/handles.inline.hpp"
  58 #include "runtime/icache.hpp"
  59 #include "runtime/init.hpp"
  60 #include "runtime/java.hpp"
  61 #include "runtime/mutexLocker.hpp"
  62 #include "runtime/os.inline.hpp"
  63 #include "runtime/safepointVerifiers.hpp"
  64 #include "runtime/vmThread.hpp"
  65 #include "sanitizers/leak.hpp"
  66 #include "services/memoryService.hpp"
  67 #include "utilities/align.hpp"
  68 #include "utilities/vmError.hpp"
  69 #include "utilities/xmlstream.hpp"
  70 #ifdef COMPILER1
  71 #include "c1/c1_Compilation.hpp"
  72 #include "c1/c1_Compiler.hpp"
  73 #endif
  74 #ifdef COMPILER2
  75 #include "opto/c2compiler.hpp"
  76 #include "opto/compile.hpp"
  77 #include "opto/node.hpp"
  78 #endif
  79 
  80 // Helper class for printing in CodeCache
  81 class CodeBlob_sizes {
  82  private:
  83   int count;
  84   int total_size;
  85   int header_size;
  86   int code_size;
  87   int stub_size;
  88   int relocation_size;
  89   int scopes_oop_size;
  90   int scopes_metadata_size;
  91   int scopes_data_size;
  92   int scopes_pcs_size;
  93 
  94  public:
  95   CodeBlob_sizes() {
  96     count            = 0;
  97     total_size       = 0;
  98     header_size      = 0;
  99     code_size        = 0;
 100     stub_size        = 0;
 101     relocation_size  = 0;
 102     scopes_oop_size  = 0;
 103     scopes_metadata_size  = 0;
 104     scopes_data_size = 0;
 105     scopes_pcs_size  = 0;
 106   }
 107 
 108   int total() const                              { return total_size; }
 109   bool is_empty() const                          { return count == 0; }
 110 
 111   void print(const char* title) const {
 112     if (is_empty()) {
 113       tty->print_cr(" #%d %s = %dK",
 114                     count,
 115                     title,
 116                     total()                 / (int)K);
 117     } else {
 118       tty->print_cr(" #%d %s = %dK (hdr %dK %d%%, loc %dK %d%%, code %dK %d%%, stub %dK %d%%, [oops %dK %d%%, metadata %dK %d%%, data %dK %d%%, pcs %dK %d%%])",
 119                     count,
 120                     title,
 121                     total()                 / (int)K,
 122                     header_size             / (int)K,
 123                     header_size             * 100 / total_size,
 124                     relocation_size         / (int)K,
 125                     relocation_size         * 100 / total_size,
 126                     code_size               / (int)K,
 127                     code_size               * 100 / total_size,
 128                     stub_size               / (int)K,
 129                     stub_size               * 100 / total_size,
 130                     scopes_oop_size         / (int)K,
 131                     scopes_oop_size         * 100 / total_size,
 132                     scopes_metadata_size    / (int)K,
 133                     scopes_metadata_size    * 100 / total_size,
 134                     scopes_data_size        / (int)K,
 135                     scopes_data_size        * 100 / total_size,
 136                     scopes_pcs_size         / (int)K,
 137                     scopes_pcs_size         * 100 / total_size);
 138     }
 139   }
 140 
 141   void add(CodeBlob* cb) {
 142     count++;
 143     total_size       += cb->size();
 144     header_size      += cb->header_size();
 145     relocation_size  += cb->relocation_size();
 146     if (cb->is_nmethod()) {
 147       nmethod* nm = cb->as_nmethod_or_null();
 148       code_size        += nm->insts_size();
 149       stub_size        += nm->stub_size();
 150 
 151       scopes_oop_size  += nm->oops_size();
 152       scopes_metadata_size  += nm->metadata_size();
 153       scopes_data_size += nm->scopes_data_size();
 154       scopes_pcs_size  += nm->scopes_pcs_size();
 155     } else {
 156       code_size        += cb->code_size();
 157     }
 158   }
 159 };
 160 
 161 // Iterate over all CodeHeaps
 162 #define FOR_ALL_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _heaps->begin(); heap != _heaps->end(); ++heap)
 163 #define FOR_ALL_ALLOCABLE_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _allocable_heaps->begin(); heap != _allocable_heaps->end(); ++heap)
 164 
 165 // Iterate over all CodeBlobs (cb) on the given CodeHeap
 166 #define FOR_ALL_BLOBS(cb, heap) for (CodeBlob* cb = first_blob(heap); cb != nullptr; cb = next_blob(heap, cb))
 167 
 168 address CodeCache::_low_bound = nullptr;
 169 address CodeCache::_high_bound = nullptr;
 170 volatile int CodeCache::_number_of_nmethods_with_dependencies = 0;
 171 ExceptionCache* volatile CodeCache::_exception_cache_purge_list = nullptr;
 172 
 173 // Initialize arrays of CodeHeap subsets
 174 GrowableArray<CodeHeap*>* CodeCache::_heaps = new(mtCode) GrowableArray<CodeHeap*> (static_cast<int>(CodeBlobType::All), mtCode);
 175 GrowableArray<CodeHeap*>* CodeCache::_nmethod_heaps = new(mtCode) GrowableArray<CodeHeap*> (static_cast<int>(CodeBlobType::All), mtCode);
 176 GrowableArray<CodeHeap*>* CodeCache::_allocable_heaps = new(mtCode) GrowableArray<CodeHeap*> (static_cast<int>(CodeBlobType::All), mtCode);
 177 
 178 static void check_min_size(const char* codeheap, size_t size, size_t required_size) {
 179   if (size < required_size) {
 180     log_debug(codecache)("Code heap (%s) size %zuK below required minimal size %zuK",
 181                          codeheap, size/K, required_size/K);
 182     err_msg title("Not enough space in %s to run VM", codeheap);
 183     err_msg message("%zuK < %zuK", size/K, required_size/K);
 184     vm_exit_during_initialization(title, message);
 185   }
 186 }
 187 
 188 struct CodeHeapInfo {
 189   size_t size;
 190   bool set;
 191   bool enabled;
 192 };
 193 
 194 static void set_size_of_unset_code_heap(CodeHeapInfo* heap, size_t available_size, size_t used_size, size_t min_size) {
 195   assert(!heap->set, "sanity");
 196   heap->size = (available_size > (used_size + min_size)) ? (available_size - used_size) : min_size;
 197 }
 198 
 199 void CodeCache::initialize_heaps() {
 200 
 201   CodeHeapInfo non_nmethod = {NonNMethodCodeHeapSize, FLAG_IS_CMDLINE(NonNMethodCodeHeapSize), true};
 202   CodeHeapInfo profiled = {ProfiledCodeHeapSize, FLAG_IS_CMDLINE(ProfiledCodeHeapSize), true};
 203   CodeHeapInfo non_profiled = {NonProfiledCodeHeapSize, FLAG_IS_CMDLINE(NonProfiledCodeHeapSize), true};
 204 
 205   const bool cache_size_set   = FLAG_IS_CMDLINE(ReservedCodeCacheSize);
 206   const size_t ps             = page_size(false, 8);
 207   const size_t min_size       = MAX2(os::vm_allocation_granularity(), ps);
 208   const size_t min_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3); // Make sure we have enough space for VM internal code
 209   size_t cache_size           = align_up(ReservedCodeCacheSize, min_size);
 210 
 211   // Prerequisites
 212   if (!heap_available(CodeBlobType::MethodProfiled)) {
 213     // For compatibility reasons, disabled tiered compilation overrides
 214     // segment size even if it is set explicitly.
 215     non_profiled.size += profiled.size;
 216     // Profiled code heap is not available, forcibly set size to 0
 217     profiled.size = 0;
 218     profiled.set = true;
 219     profiled.enabled = false;
 220   }
 221 
 222   assert(heap_available(CodeBlobType::MethodNonProfiled), "MethodNonProfiled heap is always available for segmented code heap");
 223 
 224   size_t compiler_buffer_size = 0;
 225   COMPILER1_PRESENT(compiler_buffer_size += CompilationPolicy::c1_count() * Compiler::code_buffer_size());
 226   COMPILER2_PRESENT(compiler_buffer_size += CompilationPolicy::c2_count() * C2Compiler::initial_code_buffer_size());
 227 
 228   if (!non_nmethod.set) {
 229     non_nmethod.size += compiler_buffer_size;
 230   }
 231 
 232   if (!profiled.set && !non_profiled.set) {
 233     non_profiled.size = profiled.size = (cache_size > non_nmethod.size + 2 * min_size) ?
 234                                         (cache_size - non_nmethod.size) / 2 : min_size;
 235   }
 236 
 237   if (profiled.set && !non_profiled.set) {
 238     set_size_of_unset_code_heap(&non_profiled, cache_size, non_nmethod.size + profiled.size, min_size);
 239   }
 240 
 241   if (!profiled.set && non_profiled.set) {
 242     set_size_of_unset_code_heap(&profiled, cache_size, non_nmethod.size + non_profiled.size, min_size);
 243   }
 244 
 245   // Compatibility.
 246   size_t non_nmethod_min_size = min_cache_size + compiler_buffer_size;
 247   if (!non_nmethod.set && profiled.set && non_profiled.set) {
 248     set_size_of_unset_code_heap(&non_nmethod, cache_size, profiled.size + non_profiled.size, non_nmethod_min_size);
 249   }
 250 
 251   // Note: if large page support is enabled, min_size is at least the large
 252   // page size. This ensures that the code cache is covered by large pages.
 253   non_nmethod.size = align_up(non_nmethod.size, min_size);
 254   profiled.size = align_up(profiled.size, min_size);
 255   non_profiled.size = align_up(non_profiled.size, min_size);
 256 
 257   size_t aligned_total = non_nmethod.size + profiled.size + non_profiled.size;
 258   if (!cache_size_set) {
 259     // If ReservedCodeCacheSize is explicitly set and exceeds CODE_CACHE_SIZE_LIMIT,
 260     // it is rejected by flag validation elsewhere. Here we only handle the case
 261     // where ReservedCodeCacheSize is not set explicitly, but the computed segmented
 262     // sizes (after alignment) exceed the platform limit.
 263     if (aligned_total > CODE_CACHE_SIZE_LIMIT) {
 264       err_msg message("ReservedCodeCacheSize (%zuK), Max (%zuK)."
 265                       "Segments: NonNMethod (%zuK), NonProfiled (%zuK), Profiled (%zuK).",
 266                       aligned_total/K, CODE_CACHE_SIZE_LIMIT/K,
 267                       non_nmethod.size/K, non_profiled.size/K, profiled.size/K);
 268       vm_exit_during_initialization("Code cache size exceeds platform limit", message);
 269     }
 270     if (aligned_total != cache_size) {
 271       log_info(codecache)("ReservedCodeCache size %zuK changed to total segments size NonNMethod "
 272                           "%zuK NonProfiled %zuK Profiled %zuK = %zuK",
 273                           cache_size/K, non_nmethod.size/K, non_profiled.size/K, profiled.size/K, aligned_total/K);
 274       // Adjust ReservedCodeCacheSize as necessary because it was not set explicitly
 275       cache_size = aligned_total;
 276     }
 277   } else {
 278     check_min_size("reserved code cache", cache_size, min_cache_size);
 279     // ReservedCodeCacheSize was set explicitly, so treat it as a hard cap.
 280     // If alignment causes the total to exceed the cap, shrink unset heaps
 281     // in min_size steps, never below their minimum sizes.
 282     //
 283     // A total smaller than cache_size typically happens when all segment sizes
 284     // are explicitly set. In that case there is nothing to adjust, so we
 285     // only validate the sizes.
 286     if (aligned_total > cache_size) {
 287       size_t delta = (aligned_total - cache_size) / min_size;
 288       while (delta > 0) {
 289         size_t start_delta = delta;
 290         // Do not shrink the non-nmethod heap here: running out of non-nmethod space
 291         // is more critical and may lead to unrecoverable VM errors.
 292         if (non_profiled.enabled && !non_profiled.set && non_profiled.size > min_size) {
 293           non_profiled.size -= min_size;
 294           if (--delta == 0) break;
 295         }
 296         if (profiled.enabled && !profiled.set && profiled.size > min_size) {
 297           profiled.size -= min_size;
 298           delta--;
 299         }
 300         if (delta == start_delta) {
 301           break;
 302         }
 303       }
 304       aligned_total = non_nmethod.size + profiled.size + non_profiled.size;
 305     }
 306   }
 307 
 308   log_debug(codecache)("Initializing code heaps ReservedCodeCache %zuK NonNMethod %zuK"
 309                        " NonProfiled %zuK Profiled %zuK",
 310                        cache_size/K, non_nmethod.size/K, non_profiled.size/K, profiled.size/K);
 311 
 312   // Validation
 313   // Check minimal required sizes
 314   check_min_size("non-nmethod code heap", non_nmethod.size, non_nmethod_min_size);
 315   if (profiled.enabled) {
 316     check_min_size("profiled code heap", profiled.size, min_size);
 317   }
 318   if (non_profiled.enabled) { // non_profiled.enabled is always ON for segmented code heap, leave it checked for clarity
 319     check_min_size("non-profiled code heap", non_profiled.size, min_size);
 320   }
 321 
 322   // ReservedCodeCacheSize was set explicitly, so report an error and abort if it doesn't match the segment sizes
 323   if (aligned_total != cache_size && cache_size_set) {
 324     err_msg message("NonNMethodCodeHeapSize (%zuK)", non_nmethod.size/K);
 325     if (profiled.enabled) {
 326       message.append(" + ProfiledCodeHeapSize (%zuK)", profiled.size/K);
 327     }
 328     if (non_profiled.enabled) {
 329       message.append(" + NonProfiledCodeHeapSize (%zuK)", non_profiled.size/K);
 330     }
 331     message.append(" = %zuK", aligned_total/K);
 332     message.append((aligned_total > cache_size) ? " is greater than " : " is less than ");
 333     message.append("ReservedCodeCacheSize (%zuK).", cache_size/K);
 334 
 335     vm_exit_during_initialization("Invalid code heap sizes", message);
 336   }
 337 
 338   // Compatibility. Print warning if using large pages but not able to use the size given
 339   if (UseLargePages) {
 340     const size_t lg_ps = page_size(false, 1);
 341     if (ps < lg_ps) {
 342       log_warning(codecache)("Code cache size too small for " PROPERFMT " pages. "
 343                              "Reverting to smaller page size (" PROPERFMT ").",
 344                              PROPERFMTARGS(lg_ps), PROPERFMTARGS(ps));
 345     }
 346   }
 347 
 348   FLAG_SET_ERGO(NonNMethodCodeHeapSize, non_nmethod.size);
 349   FLAG_SET_ERGO(ProfiledCodeHeapSize, profiled.size);
 350   FLAG_SET_ERGO(NonProfiledCodeHeapSize, non_profiled.size);
 351   FLAG_SET_ERGO(ReservedCodeCacheSize, cache_size);
 352 
 353   ReservedSpace rs = reserve_heap_memory(cache_size, ps);
 354 
 355   // Register CodeHeaps with LSan as we sometimes embed pointers to malloc memory.
 356   LSAN_REGISTER_ROOT_REGION(rs.base(), rs.size());
 357 
 358   size_t offset = 0;
 359   if (profiled.enabled) {
 360     ReservedSpace profiled_space = rs.partition(offset, profiled.size);
 361     offset += profiled.size;
 362     // Tier 2 and tier 3 (profiled) methods
 363     add_heap(profiled_space, "CodeHeap 'profiled nmethods'", CodeBlobType::MethodProfiled);
 364   }
 365 
 366   ReservedSpace non_method_space = rs.partition(offset, non_nmethod.size);
 367   offset += non_nmethod.size;
 368   // Non-nmethods (stubs, adapters, ...)
 369   add_heap(non_method_space, "CodeHeap 'non-nmethods'", CodeBlobType::NonNMethod);
 370 
 371   if (non_profiled.enabled) {
 372     ReservedSpace non_profiled_space  = rs.partition(offset, non_profiled.size);
 373     // Tier 1 and tier 4 (non-profiled) methods and native methods
 374     add_heap(non_profiled_space, "CodeHeap 'non-profiled nmethods'", CodeBlobType::MethodNonProfiled);
 375   }
 376 }
 377 
 378 size_t CodeCache::page_size(bool aligned, size_t min_pages) {
 379   return aligned ? os::page_size_for_region_aligned(ReservedCodeCacheSize, min_pages) :
 380                    os::page_size_for_region_unaligned(ReservedCodeCacheSize, min_pages);
 381 }
 382 
 383 ReservedSpace CodeCache::reserve_heap_memory(size_t size, size_t rs_ps) {
 384   // Align and reserve space for code cache
 385   const size_t rs_align = MAX2(rs_ps, os::vm_allocation_granularity());
 386   const size_t rs_size = align_up(size, rs_align);
 387 
 388   ReservedSpace rs = CodeMemoryReserver::reserve(rs_size, rs_align, rs_ps);
 389   if (!rs.is_reserved()) {
 390     vm_exit_during_initialization(err_msg("Could not reserve enough space for code cache (%zuK)",
 391                                           rs_size/K));
 392   }
 393 
 394   // Initialize bounds
 395   _low_bound = (address)rs.base();
 396   _high_bound = _low_bound + rs.size();
 397   return rs;
 398 }
 399 
 400 // Heaps available for allocation
 401 bool CodeCache::heap_available(CodeBlobType code_blob_type) {
 402   if (!SegmentedCodeCache) {
 403     // No segmentation: use a single code heap
 404     return (code_blob_type == CodeBlobType::All);
 405   } else if (CompilerConfig::is_interpreter_only()) {
 406     // Interpreter only: we don't need any method code heaps
 407     return (code_blob_type == CodeBlobType::NonNMethod);
 408   } else if (CompilerConfig::is_c1_profiling()) {
 409     // Tiered compilation: use all code heaps
 410     return (code_blob_type < CodeBlobType::All);
 411   } else {
 412     // No TieredCompilation: we only need the non-nmethod and non-profiled code heap
 413     return (code_blob_type == CodeBlobType::NonNMethod) ||
 414            (code_blob_type == CodeBlobType::MethodNonProfiled);
 415   }
 416 }
 417 
 418 const char* CodeCache::get_code_heap_flag_name(CodeBlobType code_blob_type) {
 419   switch(code_blob_type) {
 420   case CodeBlobType::NonNMethod:
 421     return "NonNMethodCodeHeapSize";
 422     break;
 423   case CodeBlobType::MethodNonProfiled:
 424     return "NonProfiledCodeHeapSize";
 425     break;
 426   case CodeBlobType::MethodProfiled:
 427     return "ProfiledCodeHeapSize";
 428     break;
 429   default:
 430     ShouldNotReachHere();
 431     return nullptr;
 432   }
 433 }
 434 
 435 int CodeCache::code_heap_compare(CodeHeap* const &lhs, CodeHeap* const &rhs) {
 436   if (lhs->code_blob_type() == rhs->code_blob_type()) {
 437     return (lhs > rhs) ? 1 : ((lhs < rhs) ? -1 : 0);
 438   } else {
 439     return static_cast<int>(lhs->code_blob_type()) - static_cast<int>(rhs->code_blob_type());
 440   }
 441 }
 442 
 443 void CodeCache::add_heap(CodeHeap* heap) {
 444   assert(!Universe::is_fully_initialized(), "late heap addition?");
 445 
 446   _heaps->insert_sorted<code_heap_compare>(heap);
 447 
 448   CodeBlobType type = heap->code_blob_type();
 449   if (code_blob_type_accepts_nmethod(type)) {
 450     _nmethod_heaps->insert_sorted<code_heap_compare>(heap);
 451   }
 452   if (code_blob_type_accepts_allocable(type)) {
 453     _allocable_heaps->insert_sorted<code_heap_compare>(heap);
 454   }
 455 }
 456 
 457 void CodeCache::add_heap(ReservedSpace rs, const char* name, CodeBlobType code_blob_type) {
 458   // Check if heap is needed
 459   if (!heap_available(code_blob_type)) {
 460     return;
 461   }
 462 
 463   // Create CodeHeap
 464   CodeHeap* heap = new CodeHeap(name, code_blob_type);
 465   add_heap(heap);
 466 
 467   // Reserve Space
 468   size_t size_initial = MIN2(InitialCodeCacheSize, rs.size());
 469   size_initial = align_up(size_initial, rs.page_size());
 470   if (!heap->reserve(rs, size_initial, CodeCacheSegmentSize)) {
 471     vm_exit_during_initialization(err_msg("Could not reserve enough space in %s (%zuK)",
 472                                           heap->name(), size_initial/K));
 473   }
 474 
 475   // Register the CodeHeap
 476   MemoryService::add_code_heap_memory_pool(heap, name);
 477 }
 478 
 479 CodeHeap* CodeCache::get_code_heap_containing(void* start) {
 480   FOR_ALL_HEAPS(heap) {
 481     if ((*heap)->contains(start)) {
 482       return *heap;
 483     }
 484   }
 485   return nullptr;
 486 }
 487 
 488 CodeHeap* CodeCache::get_code_heap(const void* cb) {
 489   assert(cb != nullptr, "CodeBlob is null");
 490   FOR_ALL_HEAPS(heap) {
 491     if ((*heap)->contains(cb)) {
 492       return *heap;
 493     }
 494   }
 495   ShouldNotReachHere();
 496   return nullptr;
 497 }
 498 
 499 CodeHeap* CodeCache::get_code_heap(CodeBlobType code_blob_type) {
 500   FOR_ALL_HEAPS(heap) {
 501     if ((*heap)->accepts(code_blob_type)) {
 502       return *heap;
 503     }
 504   }
 505   return nullptr;
 506 }
 507 
 508 CodeBlob* CodeCache::first_blob(CodeHeap* heap) {
 509   assert_locked_or_safepoint(CodeCache_lock);
 510   assert(heap != nullptr, "heap is null");
 511   return (CodeBlob*)heap->first();
 512 }
 513 
 514 CodeBlob* CodeCache::first_blob(CodeBlobType code_blob_type) {
 515   if (heap_available(code_blob_type)) {
 516     return first_blob(get_code_heap(code_blob_type));
 517   } else {
 518     return nullptr;
 519   }
 520 }
 521 
 522 CodeBlob* CodeCache::next_blob(CodeHeap* heap, CodeBlob* cb) {
 523   assert_locked_or_safepoint(CodeCache_lock);
 524   assert(heap != nullptr, "heap is null");
 525   return (CodeBlob*)heap->next(cb);
 526 }
 527 
 528 /**
 529  * Do not seize the CodeCache lock here--if the caller has not
 530  * already done so, we are going to lose bigtime, since the code
 531  * cache will contain a garbage CodeBlob until the caller can
 532  * run the constructor for the CodeBlob subclass he is busy
 533  * instantiating.
 534  */
 535 CodeBlob* CodeCache::allocate(uint size, CodeBlobType code_blob_type, bool handle_alloc_failure, CodeBlobType orig_code_blob_type) {
 536   assert_locked_or_safepoint(CodeCache_lock);
 537   assert(size > 0, "Code cache allocation request must be > 0");
 538   if (size == 0) {
 539     return nullptr;
 540   }
 541   CodeBlob* cb = nullptr;
 542 
 543   // Get CodeHeap for the given CodeBlobType
 544   CodeHeap* heap = get_code_heap(code_blob_type);
 545   assert(heap != nullptr, "heap is null");
 546 
 547   while (true) {
 548     cb = (CodeBlob*)heap->allocate(size);
 549     if (cb != nullptr) break;
 550     if (!heap->expand_by(CodeCacheExpansionSize)) {
 551       // Save original type for error reporting
 552       if (orig_code_blob_type == CodeBlobType::All) {
 553         orig_code_blob_type = code_blob_type;
 554       }
 555       // Expansion failed
 556       if (SegmentedCodeCache) {
 557         // Fallback solution: Try to store code in another code heap.
 558         // NonNMethod -> MethodNonProfiled -> MethodProfiled (-> MethodNonProfiled)
 559         CodeBlobType type = code_blob_type;
 560         switch (type) {
 561         case CodeBlobType::NonNMethod:
 562           type = CodeBlobType::MethodNonProfiled;
 563           break;
 564         case CodeBlobType::MethodNonProfiled:
 565           type = CodeBlobType::MethodProfiled;
 566           break;
 567         case CodeBlobType::MethodProfiled:
 568           // Avoid loop if we already tried that code heap
 569           if (type == orig_code_blob_type) {
 570             type = CodeBlobType::MethodNonProfiled;
 571           }
 572           break;
 573         default:
 574           break;
 575         }
 576         if (type != code_blob_type && type != orig_code_blob_type && heap_available(type)) {
 577           if (PrintCodeCacheExtension) {
 578             tty->print_cr("Extension of %s failed. Trying to allocate in %s.",
 579                           heap->name(), get_code_heap(type)->name());
 580           }
 581           return allocate(size, type, handle_alloc_failure, orig_code_blob_type);
 582         }
 583       }
 584       if (handle_alloc_failure) {
 585         MutexUnlocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 586         CompileBroker::handle_full_code_cache(orig_code_blob_type);
 587       }
 588       return nullptr;
 589     } else {
 590       OrderAccess::release(); // ensure heap expansion is visible to an asynchronous observer (e.g. CodeHeapPool::get_memory_usage())
 591     }
 592     if (PrintCodeCacheExtension) {
 593       ResourceMark rm;
 594       if (_nmethod_heaps->length() >= 1) {
 595         tty->print("%s", heap->name());
 596       } else {
 597         tty->print("CodeCache");
 598       }
 599       tty->print_cr(" extended to [" INTPTR_FORMAT ", " INTPTR_FORMAT "] (%zd bytes)",
 600                     (intptr_t)heap->low_boundary(), (intptr_t)heap->high(),
 601                     (address)heap->high() - (address)heap->low_boundary());
 602     }
 603   }
 604   print_trace("allocation", cb, size);
 605   return cb;
 606 }
 607 
 608 void CodeCache::free(CodeBlob* cb) {
 609   assert_locked_or_safepoint(CodeCache_lock);
 610   CodeHeap* heap = get_code_heap(cb);
 611   print_trace("free", cb);
 612   if (cb->is_nmethod()) {
 613     heap->set_nmethod_count(heap->nmethod_count() - 1);
 614     if (((nmethod *)cb)->has_dependencies()) {
 615       AtomicAccess::dec(&_number_of_nmethods_with_dependencies);
 616     }
 617   }
 618   if (cb->is_adapter_blob()) {
 619     heap->set_adapter_count(heap->adapter_count() - 1);
 620   }
 621 
 622   cb->~CodeBlob();
 623   // Get heap for given CodeBlob and deallocate
 624   heap->deallocate(cb);
 625 
 626   assert(heap->blob_count() >= 0, "sanity check");
 627 }
 628 
 629 void CodeCache::free_unused_tail(CodeBlob* cb, size_t used) {
 630   assert_locked_or_safepoint(CodeCache_lock);
 631   guarantee(cb->is_buffer_blob() && strncmp("Interpreter", cb->name(), 11) == 0, "Only possible for interpreter!");
 632   print_trace("free_unused_tail", cb);
 633 
 634   // We also have to account for the extra space (i.e. header) used by the CodeBlob
 635   // which provides the memory (see BufferBlob::create() in codeBlob.cpp).
 636   used += CodeBlob::align_code_offset(cb->header_size());
 637 
 638   // Get heap for given CodeBlob and deallocate its unused tail
 639   get_code_heap(cb)->deallocate_tail(cb, used);
 640   // Adjust the sizes of the CodeBlob
 641   cb->adjust_size(used);
 642 }
 643 
 644 void CodeCache::commit(CodeBlob* cb) {
 645   // this is called by nmethod::nmethod, which must already own CodeCache_lock
 646   assert_locked_or_safepoint(CodeCache_lock);
 647   CodeHeap* heap = get_code_heap(cb);
 648   if (cb->is_nmethod()) {
 649     heap->set_nmethod_count(heap->nmethod_count() + 1);
 650     if (((nmethod *)cb)->has_dependencies()) {
 651       AtomicAccess::inc(&_number_of_nmethods_with_dependencies);
 652     }
 653   }
 654   if (cb->is_adapter_blob()) {
 655     heap->set_adapter_count(heap->adapter_count() + 1);
 656   }
 657 }
 658 
 659 bool CodeCache::contains(void *p) {
 660   // S390 uses contains() in current_frame(), which is used before
 661   // code cache initialization if NativeMemoryTracking=detail is set.
 662   S390_ONLY(if (_heaps == nullptr) return false;)
 663   // It should be ok to call contains without holding a lock.
 664   FOR_ALL_HEAPS(heap) {
 665     if ((*heap)->contains(p)) {
 666       return true;
 667     }
 668   }
 669   return false;
 670 }
 671 
 672 bool CodeCache::contains(nmethod *nm) {
 673   return contains((void *)nm);
 674 }
 675 
 676 // This method is safe to call without holding the CodeCache_lock. It only depends on the _segmap to contain
 677 // valid indices, which it will always do, as long as the CodeBlob is not in the process of being recycled.
 678 CodeBlob* CodeCache::find_blob(void* start) {
 679   // NMT can walk the stack before code cache is created
 680   if (_heaps != nullptr) {
 681     CodeHeap* heap = get_code_heap_containing(start);
 682     if (heap != nullptr) {
 683       return heap->find_blob(start);
 684     }
 685   }
 686   return nullptr;
 687 }
 688 
 689 nmethod* CodeCache::find_nmethod(void* start) {
 690   CodeBlob* cb = find_blob(start);
 691   assert(cb == nullptr || cb->is_nmethod(), "did not find an nmethod");
 692   return (nmethod*)cb;
 693 }
 694 
 695 void CodeCache::blobs_do(void f(CodeBlob* nm)) {
 696   assert_locked_or_safepoint(CodeCache_lock);
 697   FOR_ALL_HEAPS(heap) {
 698     FOR_ALL_BLOBS(cb, *heap) {
 699       f(cb);
 700     }
 701   }
 702 }
 703 
 704 void CodeCache::nmethods_do(void f(nmethod* nm)) {
 705   assert_locked_or_safepoint(CodeCache_lock);
 706   NMethodIterator iter(NMethodIterator::all);
 707   while(iter.next()) {
 708     f(iter.method());
 709   }
 710 }
 711 
 712 void CodeCache::nmethods_do(NMethodClosure* cl) {
 713   assert_locked_or_safepoint(CodeCache_lock);
 714   NMethodIterator iter(NMethodIterator::all);
 715   while(iter.next()) {
 716     cl->do_nmethod(iter.method());
 717   }
 718 }
 719 
 720 void CodeCache::metadata_do(MetadataClosure* f) {
 721   assert_locked_or_safepoint(CodeCache_lock);
 722   NMethodIterator iter(NMethodIterator::all);
 723   while(iter.next()) {
 724     iter.method()->metadata_do(f);
 725   }
 726 }
 727 
 728 // Calculate the number of GCs after which an nmethod is expected to have been
 729 // used in order to not be classed as cold.
 730 void CodeCache::update_cold_gc_count() {
 731   if (!MethodFlushing || !UseCodeCacheFlushing || NmethodSweepActivity == 0) {
 732     // No aging
 733     return;
 734   }
 735 
 736   size_t last_used = _last_unloading_used;
 737   double last_time = _last_unloading_time;
 738 
 739   double time = os::elapsedTime();
 740 
 741   size_t free = unallocated_capacity();
 742   size_t max = max_capacity();
 743   size_t used = max - free;
 744   double gc_interval = time - last_time;
 745 
 746   _unloading_threshold_gc_requested = false;
 747   _last_unloading_time = time;
 748   _last_unloading_used = used;
 749 
 750   if (last_time == 0.0) {
 751     // The first GC doesn't have enough information to make good
 752     // decisions, so just keep everything afloat
 753     log_info(codecache)("Unknown code cache pressure; don't age code");
 754     return;
 755   }
 756 
 757   if (gc_interval <= 0.0 || last_used >= used) {
 758     // Dodge corner cases where there is no pressure or negative pressure
 759     // on the code cache. Just don't unload when this happens.
 760     _cold_gc_count = INT_MAX;
 761     log_info(codecache)("No code cache pressure; don't age code");
 762     return;
 763   }
 764 
 765   double allocation_rate = (used - last_used) / gc_interval;
 766 
 767   _unloading_allocation_rates.add(allocation_rate);
 768   _unloading_gc_intervals.add(gc_interval);
 769 
 770   size_t aggressive_sweeping_free_threshold = StartAggressiveSweepingAt / 100.0 * max;
 771   if (free < aggressive_sweeping_free_threshold) {
 772     // We are already in the red zone; be very aggressive to avoid disaster
 773     // But not more aggressive than 2. This ensures that an nmethod must
 774     // have been unused at least between two GCs to be considered cold still.
 775     _cold_gc_count = 2;
 776     log_info(codecache)("Code cache critically low; use aggressive aging");
 777     return;
 778   }
 779 
 780   // The code cache has an expected time for cold nmethods to "time out"
 781   // when they have not been used. The time for nmethods to time out
 782   // depends on how long we expect we can keep allocating code until
 783   // aggressive sweeping starts, based on sampled allocation rates.
 784   double average_gc_interval = _unloading_gc_intervals.avg();
 785   double average_allocation_rate = _unloading_allocation_rates.avg();
 786   double time_to_aggressive = ((double)(free - aggressive_sweeping_free_threshold)) / average_allocation_rate;
 787   double cold_timeout = time_to_aggressive / NmethodSweepActivity;
 788 
 789   // Convert time to GC cycles, and crop at INT_MAX. The reason for
 790   // that is that the _cold_gc_count will be added to an epoch number
 791   // and that addition must not overflow, or we can crash the VM.
 792   // But not more aggressive than 2. This ensures that an nmethod must
 793   // have been unused at least between two GCs to be considered cold still.
 794   _cold_gc_count = MAX2(MIN2((uint64_t)(cold_timeout / average_gc_interval), (uint64_t)INT_MAX), (uint64_t)2);
 795 
 796   double used_ratio = double(used) / double(max);
 797   double last_used_ratio = double(last_used) / double(max);
 798   log_info(codecache)("Allocation rate: %.3f KB/s, time to aggressive unloading: %.3f s, cold timeout: %.3f s, cold gc count: " UINT64_FORMAT
 799                       ", used: %.3f MB (%.3f%%), last used: %.3f MB (%.3f%%), gc interval: %.3f s",
 800                       average_allocation_rate / K, time_to_aggressive, cold_timeout, _cold_gc_count,
 801                       double(used) / M, used_ratio * 100.0, double(last_used) / M, last_used_ratio * 100.0, average_gc_interval);
 802 
 803 }
 804 
 805 uint64_t CodeCache::cold_gc_count() {
 806   return _cold_gc_count;
 807 }
 808 
 809 void CodeCache::gc_on_allocation() {
 810   if (!is_init_completed()) {
 811     // Let's not heuristically trigger GCs before the JVM is ready for GCs, no matter what
 812     return;
 813   }
 814 
 815   size_t free = unallocated_capacity();
 816   size_t max = max_capacity();
 817   size_t used = max - free;
 818   double free_ratio = double(free) / double(max);
 819   if (free_ratio <= StartAggressiveSweepingAt / 100.0)  {
 820     // In case the GC is concurrent, we make sure only one thread requests the GC.
 821     if (AtomicAccess::cmpxchg(&_unloading_threshold_gc_requested, false, true) == false) {
 822       log_info(codecache)("Triggering aggressive GC due to having only %.3f%% free memory", free_ratio * 100.0);
 823       Universe::heap()->collect(GCCause::_codecache_GC_aggressive);
 824     }
 825     return;
 826   }
 827 
 828   size_t last_used = _last_unloading_used;
 829   if (last_used >= used) {
 830     // No increase since last GC; no need to sweep yet
 831     return;
 832   }
 833   size_t allocated_since_last = used - last_used;
 834   double allocated_since_last_ratio = double(allocated_since_last) / double(max);
 835   double threshold = SweeperThreshold / 100.0;
 836   double used_ratio = double(used) / double(max);
 837   double last_used_ratio = double(last_used) / double(max);
 838   if (used_ratio > threshold) {
 839     // After threshold is reached, scale it by free_ratio so that more aggressive
 840     // GC is triggered as we approach code cache exhaustion
 841     threshold *= free_ratio;
 842   }
 843   // If code cache has been allocated without any GC at all, let's make sure
 844   // it is eventually invoked to avoid trouble.
 845   if (allocated_since_last_ratio > threshold) {
 846     // In case the GC is concurrent, we make sure only one thread requests the GC.
 847     if (AtomicAccess::cmpxchg(&_unloading_threshold_gc_requested, false, true) == false) {
 848       log_info(codecache)("Triggering threshold (%.3f%%) GC due to allocating %.3f%% since last unloading (%.3f%% used -> %.3f%% used)",
 849                           threshold * 100.0, allocated_since_last_ratio * 100.0, last_used_ratio * 100.0, used_ratio * 100.0);
 850       Universe::heap()->collect(GCCause::_codecache_GC_threshold);
 851     }
 852   }
 853 }
 854 
 855 // We initialize the _gc_epoch to 2, because previous_completed_gc_marking_cycle
 856 // subtracts the value by 2, and the type is unsigned. We don't want underflow.
 857 //
 858 // Odd values mean that marking is in progress, and even values mean that no
 859 // marking is currently active.
 860 uint64_t CodeCache::_gc_epoch = 2;
 861 
 862 // How many GCs after an nmethod has not been used, do we consider it cold?
 863 uint64_t CodeCache::_cold_gc_count = INT_MAX;
 864 
 865 double CodeCache::_last_unloading_time = 0.0;
 866 size_t CodeCache::_last_unloading_used = 0;
 867 volatile bool CodeCache::_unloading_threshold_gc_requested = false;
 868 TruncatedSeq CodeCache::_unloading_gc_intervals(10 /* samples */);
 869 TruncatedSeq CodeCache::_unloading_allocation_rates(10 /* samples */);
 870 
 871 uint64_t CodeCache::gc_epoch() {
 872   return _gc_epoch;
 873 }
 874 
 875 bool CodeCache::is_gc_marking_cycle_active() {
 876   // Odd means that marking is active
 877   return (_gc_epoch % 2) == 1;
 878 }
 879 
 880 uint64_t CodeCache::previous_completed_gc_marking_cycle() {
 881   if (is_gc_marking_cycle_active()) {
 882     return _gc_epoch - 2;
 883   } else {
 884     return _gc_epoch - 1;
 885   }
 886 }
 887 
 888 void CodeCache::on_gc_marking_cycle_start() {
 889   assert(!is_gc_marking_cycle_active(), "Previous marking cycle never ended");
 890   ++_gc_epoch;
 891 }
 892 
 893 // Once started the code cache marking cycle must only be finished after marking of
 894 // the java heap is complete. Otherwise nmethods could appear to be not on stack even
 895 // if they have frames in continuation StackChunks that were not yet visited.
 896 void CodeCache::on_gc_marking_cycle_finish() {
 897   assert(is_gc_marking_cycle_active(), "Marking cycle started before last one finished");
 898   ++_gc_epoch;
 899   update_cold_gc_count();
 900 }
 901 
 902 void CodeCache::arm_all_nmethods() {
 903   BarrierSet::barrier_set()->barrier_set_nmethod()->arm_all_nmethods();
 904 }
 905 
 906 // Mark nmethods for unloading if they contain otherwise unreachable oops.
 907 void CodeCache::do_unloading(bool unloading_occurred) {
 908   assert_locked_or_safepoint(CodeCache_lock);
 909   NMethodIterator iter(NMethodIterator::all);
 910   while(iter.next()) {
 911     iter.method()->do_unloading(unloading_occurred);
 912   }
 913 }
 914 
 915 void CodeCache::verify_clean_inline_caches() {
 916 #ifdef ASSERT
 917   if (!VerifyInlineCaches) return;
 918   NMethodIterator iter(NMethodIterator::not_unloading);
 919   while(iter.next()) {
 920     nmethod* nm = iter.method();
 921     nm->verify_clean_inline_caches();
 922     nm->verify();
 923   }
 924 #endif
 925 }
 926 
 927 // Defer freeing of concurrently cleaned ExceptionCache entries until
 928 // after a global handshake operation.
 929 void CodeCache::release_exception_cache(ExceptionCache* entry) {
 930   if (SafepointSynchronize::is_at_safepoint()) {
 931     delete entry;
 932   } else {
 933     for (;;) {
 934       ExceptionCache* purge_list_head = AtomicAccess::load(&_exception_cache_purge_list);
 935       entry->set_purge_list_next(purge_list_head);
 936       if (AtomicAccess::cmpxchg(&_exception_cache_purge_list, purge_list_head, entry) == purge_list_head) {
 937         break;
 938       }
 939     }
 940   }
 941 }
 942 
 943 // Delete exception caches that have been concurrently unlinked,
 944 // followed by a global handshake operation.
 945 void CodeCache::purge_exception_caches() {
 946   ExceptionCache* curr = _exception_cache_purge_list;
 947   while (curr != nullptr) {
 948     ExceptionCache* next = curr->purge_list_next();
 949     delete curr;
 950     curr = next;
 951   }
 952   _exception_cache_purge_list = nullptr;
 953 }
 954 
 955 // Restart compiler if possible and required..
 956 void CodeCache::maybe_restart_compiler(size_t freed_memory) {
 957 
 958   // Try to start the compiler again if we freed any memory
 959   if (!CompileBroker::should_compile_new_jobs() && freed_memory != 0) {
 960     CompileBroker::set_should_compile_new_jobs(CompileBroker::run_compilation);
 961     log_info(codecache)("Restarting compiler");
 962     EventJITRestart event;
 963     event.set_freedMemory(freed_memory);
 964     event.set_codeCacheMaxCapacity(CodeCache::max_capacity());
 965     event.commit();
 966   }
 967 }
 968 
 969 uint8_t CodeCache::_unloading_cycle = 1;
 970 
 971 void CodeCache::increment_unloading_cycle() {
 972   // 2-bit value (see IsUnloadingState in nmethod.cpp for details)
 973   // 0 is reserved for new methods.
 974   _unloading_cycle = (_unloading_cycle + 1) % 4;
 975   if (_unloading_cycle == 0) {
 976     _unloading_cycle = 1;
 977   }
 978 }
 979 
 980 CodeCache::UnlinkingScope::UnlinkingScope(BoolObjectClosure* is_alive)
 981   : _is_unloading_behaviour(is_alive)
 982 {
 983   _saved_behaviour = IsUnloadingBehaviour::current();
 984   IsUnloadingBehaviour::set_current(&_is_unloading_behaviour);
 985   increment_unloading_cycle();
 986   DependencyContext::cleaning_start();
 987 }
 988 
 989 CodeCache::UnlinkingScope::~UnlinkingScope() {
 990   IsUnloadingBehaviour::set_current(_saved_behaviour);
 991   DependencyContext::cleaning_end();
 992 }
 993 
 994 void CodeCache::verify_oops() {
 995   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 996   VerifyOopClosure voc;
 997   NMethodIterator iter(NMethodIterator::not_unloading);
 998   while(iter.next()) {
 999     nmethod* nm = iter.method();
1000     nm->oops_do(&voc);
1001     nm->verify_oop_relocations();
1002   }
1003 }
1004 
1005 int CodeCache::blob_count(CodeBlobType code_blob_type) {
1006   CodeHeap* heap = get_code_heap(code_blob_type);
1007   return (heap != nullptr) ? heap->blob_count() : 0;
1008 }
1009 
1010 int CodeCache::blob_count() {
1011   int count = 0;
1012   FOR_ALL_HEAPS(heap) {
1013     count += (*heap)->blob_count();
1014   }
1015   return count;
1016 }
1017 
1018 int CodeCache::nmethod_count(CodeBlobType code_blob_type) {
1019   CodeHeap* heap = get_code_heap(code_blob_type);
1020   return (heap != nullptr) ? heap->nmethod_count() : 0;
1021 }
1022 
1023 int CodeCache::nmethod_count() {
1024   int count = 0;
1025   for (CodeHeap* heap : *_nmethod_heaps) {
1026     count += heap->nmethod_count();
1027   }
1028   return count;
1029 }
1030 
1031 int CodeCache::adapter_count(CodeBlobType code_blob_type) {
1032   CodeHeap* heap = get_code_heap(code_blob_type);
1033   return (heap != nullptr) ? heap->adapter_count() : 0;
1034 }
1035 
1036 int CodeCache::adapter_count() {
1037   int count = 0;
1038   FOR_ALL_HEAPS(heap) {
1039     count += (*heap)->adapter_count();
1040   }
1041   return count;
1042 }
1043 
1044 address CodeCache::low_bound(CodeBlobType code_blob_type) {
1045   CodeHeap* heap = get_code_heap(code_blob_type);
1046   return (heap != nullptr) ? (address)heap->low_boundary() : nullptr;
1047 }
1048 
1049 address CodeCache::high_bound(CodeBlobType code_blob_type) {
1050   CodeHeap* heap = get_code_heap(code_blob_type);
1051   return (heap != nullptr) ? (address)heap->high_boundary() : nullptr;
1052 }
1053 
1054 size_t CodeCache::capacity() {
1055   size_t cap = 0;
1056   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1057     cap += (*heap)->capacity();
1058   }
1059   return cap;
1060 }
1061 
1062 size_t CodeCache::unallocated_capacity(CodeBlobType code_blob_type) {
1063   CodeHeap* heap = get_code_heap(code_blob_type);
1064   return (heap != nullptr) ? heap->unallocated_capacity() : 0;
1065 }
1066 
1067 size_t CodeCache::unallocated_capacity() {
1068   size_t unallocated_cap = 0;
1069   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1070     unallocated_cap += (*heap)->unallocated_capacity();
1071   }
1072   return unallocated_cap;
1073 }
1074 
1075 size_t CodeCache::max_capacity() {
1076   size_t max_cap = 0;
1077   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1078     max_cap += (*heap)->max_capacity();
1079   }
1080   return max_cap;
1081 }
1082 
1083 bool CodeCache::is_non_nmethod(address addr) {
1084   CodeHeap* blob = get_code_heap(CodeBlobType::NonNMethod);
1085   return blob->contains(addr);
1086 }
1087 
1088 size_t CodeCache::max_distance_to_non_nmethod() {
1089   if (!SegmentedCodeCache) {
1090     return ReservedCodeCacheSize;
1091   } else {
1092     CodeHeap* blob = get_code_heap(CodeBlobType::NonNMethod);
1093     // the max distance is minimized by placing the NonNMethod segment
1094     // in between MethodProfiled and MethodNonProfiled segments
1095     size_t dist1 = (size_t)blob->high() - (size_t)_low_bound;
1096     size_t dist2 = (size_t)_high_bound - (size_t)blob->low();
1097     return dist1 > dist2 ? dist1 : dist2;
1098   }
1099 }
1100 
1101 // Returns the reverse free ratio. E.g., if 25% (1/4) of the code cache
1102 // is free, reverse_free_ratio() returns 4.
1103 // Since code heap for each type of code blobs falls forward to the next
1104 // type of code heap, return the reverse free ratio for the entire
1105 // code cache.
1106 double CodeCache::reverse_free_ratio() {
1107   double unallocated = MAX2((double)unallocated_capacity(), 1.0); // Avoid division by 0;
1108   double max = (double)max_capacity();
1109   double result = max / unallocated;
1110   assert (max >= unallocated, "Must be");
1111   assert (result >= 1.0, "reverse_free_ratio must be at least 1. It is %f", result);
1112   return result;
1113 }
1114 
1115 size_t CodeCache::bytes_allocated_in_freelists() {
1116   size_t allocated_bytes = 0;
1117   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1118     allocated_bytes += (*heap)->allocated_in_freelist();
1119   }
1120   return allocated_bytes;
1121 }
1122 
1123 int CodeCache::allocated_segments() {
1124   int number_of_segments = 0;
1125   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1126     number_of_segments += (*heap)->allocated_segments();
1127   }
1128   return number_of_segments;
1129 }
1130 
1131 size_t CodeCache::freelists_length() {
1132   size_t length = 0;
1133   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1134     length += (*heap)->freelist_length();
1135   }
1136   return length;
1137 }
1138 
1139 void icache_init();
1140 
1141 void CodeCache::initialize() {
1142   assert(CodeCacheSegmentSize >= CodeEntryAlignment, "CodeCacheSegmentSize must be large enough to align entry points");
1143 #ifdef COMPILER2
1144   assert(CodeCacheSegmentSize >= (size_t)OptoLoopAlignment,  "CodeCacheSegmentSize must be large enough to align inner loops");
1145 #endif
1146   assert(CodeCacheSegmentSize >= sizeof(jdouble),    "CodeCacheSegmentSize must be large enough to align constants");
1147   // This was originally just a check of the alignment, causing failure, instead, round
1148   // the code cache to the page size.  In particular, Solaris is moving to a larger
1149   // default page size.
1150   CodeCacheExpansionSize = align_up(CodeCacheExpansionSize, os::vm_page_size());
1151 
1152   if (SegmentedCodeCache) {
1153     // Use multiple code heaps
1154     initialize_heaps();
1155   } else {
1156     // Use a single code heap
1157     FLAG_SET_ERGO(NonNMethodCodeHeapSize, (uintx)os::vm_page_size());
1158     FLAG_SET_ERGO(ProfiledCodeHeapSize, 0);
1159     FLAG_SET_ERGO(NonProfiledCodeHeapSize, 0);
1160 
1161     // If InitialCodeCacheSize is equal to ReservedCodeCacheSize, then it's more likely
1162     // users want to use the largest available page.
1163     const size_t min_pages = (InitialCodeCacheSize == ReservedCodeCacheSize) ? 1 : 8;
1164     ReservedSpace rs = reserve_heap_memory(ReservedCodeCacheSize, page_size(false, min_pages));
1165     // Register CodeHeaps with LSan as we sometimes embed pointers to malloc memory.
1166     LSAN_REGISTER_ROOT_REGION(rs.base(), rs.size());
1167     add_heap(rs, "CodeCache", CodeBlobType::All);
1168   }
1169 
1170   // Initialize ICache flush mechanism
1171   // This service is needed for os::register_code_area
1172   icache_init();
1173 
1174   // Give OS a chance to register generated code area.
1175   // This is used on Windows 64 bit platforms to register
1176   // Structured Exception Handlers for our generated code.
1177   os::register_code_area((char*)low_bound(), (char*)high_bound());
1178 }
1179 
1180 void codeCache_init() {
1181   CodeCache::initialize();
1182 }
1183 
1184 //------------------------------------------------------------------------------------------------
1185 
1186 bool CodeCache::has_nmethods_with_dependencies() {
1187   return AtomicAccess::load_acquire(&_number_of_nmethods_with_dependencies) != 0;
1188 }
1189 
1190 void CodeCache::clear_inline_caches() {
1191   assert_locked_or_safepoint(CodeCache_lock);
1192   NMethodIterator iter(NMethodIterator::not_unloading);
1193   while(iter.next()) {
1194     iter.method()->clear_inline_caches();
1195   }
1196 }
1197 
1198 // Only used by whitebox API
1199 void CodeCache::cleanup_inline_caches_whitebox() {
1200   assert_locked_or_safepoint(CodeCache_lock);
1201   NMethodIterator iter(NMethodIterator::not_unloading);
1202   while(iter.next()) {
1203     iter.method()->cleanup_inline_caches_whitebox();
1204   }
1205 }
1206 
1207 // Keeps track of time spent for checking dependencies
1208 NOT_PRODUCT(static elapsedTimer dependentCheckTime;)
1209 
1210 #ifndef PRODUCT
1211 // Check if any of live methods dependencies have been invalidated.
1212 // (this is expensive!)
1213 static void check_live_nmethods_dependencies(DepChange& changes) {
1214   // Checked dependencies are allocated into this ResourceMark
1215   ResourceMark rm;
1216 
1217   // Turn off dependency tracing while actually testing dependencies.
1218   FlagSetting fs(Dependencies::_verify_in_progress, true);
1219 
1220   typedef HashTable<DependencySignature, int, 11027,
1221                             AnyObj::RESOURCE_AREA, mtInternal,
1222                             &DependencySignature::hash,
1223                             &DependencySignature::equals> DepTable;
1224 
1225   DepTable* table = new DepTable();
1226 
1227   // Iterate over live nmethods and check dependencies of all nmethods that are not
1228   // marked for deoptimization. A particular dependency is only checked once.
1229   NMethodIterator iter(NMethodIterator::not_unloading);
1230   while(iter.next()) {
1231     nmethod* nm = iter.method();
1232     // Only notify for live nmethods
1233     if (!nm->is_marked_for_deoptimization()) {
1234       for (Dependencies::DepStream deps(nm); deps.next(); ) {
1235         // Construct abstraction of a dependency.
1236         DependencySignature* current_sig = new DependencySignature(deps);
1237 
1238         // Determine if dependency is already checked. table->put(...) returns
1239         // 'true' if the dependency is added (i.e., was not in the hashtable).
1240         if (table->put(*current_sig, 1)) {
1241           if (deps.check_dependency() != nullptr) {
1242             // Dependency checking failed. Print out information about the failed
1243             // dependency and finally fail with an assert. We can fail here, since
1244             // dependency checking is never done in a product build.
1245             tty->print_cr("Failed dependency:");
1246             changes.print();
1247             nm->print();
1248             nm->print_dependencies_on(tty);
1249             assert(false, "Should have been marked for deoptimization");
1250           }
1251         }
1252       }
1253     }
1254   }
1255 }
1256 #endif
1257 
1258 void CodeCache::mark_for_deoptimization(DeoptimizationScope* deopt_scope, KlassDepChange& changes) {
1259   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1260 
1261   // search the hierarchy looking for nmethods which are affected by the loading of this class
1262 
1263   // then search the interfaces this class implements looking for nmethods
1264   // which might be dependent of the fact that an interface only had one
1265   // implementor.
1266   // nmethod::check_all_dependencies works only correctly, if no safepoint
1267   // can happen
1268   NoSafepointVerifier nsv;
1269   for (DepChange::ContextStream str(changes, nsv); str.next(); ) {
1270     InstanceKlass* d = str.klass();
1271     d->mark_dependent_nmethods(deopt_scope, changes);
1272   }
1273 
1274 #ifndef PRODUCT
1275   if (VerifyDependencies) {
1276     // Object pointers are used as unique identifiers for dependency arguments. This
1277     // is only possible if no safepoint, i.e., GC occurs during the verification code.
1278     dependentCheckTime.start();
1279     check_live_nmethods_dependencies(changes);
1280     dependentCheckTime.stop();
1281   }
1282 #endif
1283 }
1284 
1285 #if INCLUDE_JVMTI
1286 // RedefineClasses support for saving nmethods that are dependent on "old" methods.
1287 // We don't really expect this table to grow very large.  If it does, it can become a hashtable.
1288 static GrowableArray<nmethod*>* old_nmethod_table = nullptr;
1289 
1290 static void add_to_old_table(nmethod* c) {
1291   if (old_nmethod_table == nullptr) {
1292     old_nmethod_table = new (mtCode) GrowableArray<nmethod*>(100, mtCode);
1293   }
1294   old_nmethod_table->push(c);
1295 }
1296 
1297 static void reset_old_method_table() {
1298   if (old_nmethod_table != nullptr) {
1299     delete old_nmethod_table;
1300     old_nmethod_table = nullptr;
1301   }
1302 }
1303 
1304 // Remove this method when flushed.
1305 void CodeCache::unregister_old_nmethod(nmethod* c) {
1306   assert_lock_strong(CodeCache_lock);
1307   if (old_nmethod_table != nullptr) {
1308     int index = old_nmethod_table->find(c);
1309     if (index != -1) {
1310       old_nmethod_table->delete_at(index);
1311     }
1312   }
1313 }
1314 
1315 void CodeCache::old_nmethods_do(MetadataClosure* f) {
1316   // Walk old method table and mark those on stack.
1317   int length = 0;
1318   if (old_nmethod_table != nullptr) {
1319     length = old_nmethod_table->length();
1320     for (int i = 0; i < length; i++) {
1321       // Walk all methods saved on the last pass.  Concurrent class unloading may
1322       // also be looking at this method's metadata, so don't delete it yet if
1323       // it is marked as unloaded.
1324       old_nmethod_table->at(i)->metadata_do(f);
1325     }
1326   }
1327   log_debug(redefine, class, nmethod)("Walked %d nmethods for mark_on_stack", length);
1328 }
1329 
1330 // Walk compiled methods and mark dependent methods for deoptimization.
1331 void CodeCache::mark_dependents_for_evol_deoptimization(DeoptimizationScope* deopt_scope) {
1332   assert(SafepointSynchronize::is_at_safepoint(), "Can only do this at a safepoint!");
1333   // Each redefinition creates a new set of nmethods that have references to "old" Methods
1334   // So delete old method table and create a new one.
1335   reset_old_method_table();
1336 
1337   NMethodIterator iter(NMethodIterator::all);
1338   while(iter.next()) {
1339     nmethod* nm = iter.method();
1340     // Walk all alive nmethods to check for old Methods.
1341     // This includes methods whose inline caches point to old methods, so
1342     // inline cache clearing is unnecessary.
1343     if (nm->has_evol_metadata()) {
1344       deopt_scope->mark(nm);
1345       add_to_old_table(nm);
1346     }
1347   }
1348 }
1349 
1350 void CodeCache::mark_all_nmethods_for_evol_deoptimization(DeoptimizationScope* deopt_scope) {
1351   assert(SafepointSynchronize::is_at_safepoint(), "Can only do this at a safepoint!");
1352   NMethodIterator iter(NMethodIterator::all);
1353   while(iter.next()) {
1354     nmethod* nm = iter.method();
1355     if (!nm->method()->is_method_handle_intrinsic()) {
1356       if (nm->can_be_deoptimized()) {
1357         deopt_scope->mark(nm);
1358       }
1359       if (nm->has_evol_metadata()) {
1360         add_to_old_table(nm);
1361       }
1362     }
1363   }
1364 }
1365 
1366 #endif // INCLUDE_JVMTI
1367 
1368 // Mark methods for deopt (if safe or possible).
1369 void CodeCache::mark_all_nmethods_for_deoptimization(DeoptimizationScope* deopt_scope) {
1370   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1371   NMethodIterator iter(NMethodIterator::not_unloading);
1372   while(iter.next()) {
1373     nmethod* nm = iter.method();
1374     if (!nm->is_native_method()) {
1375       deopt_scope->mark(nm);
1376     }
1377   }
1378 }
1379 
1380 void CodeCache::mark_for_deoptimization(DeoptimizationScope* deopt_scope, Method* dependee) {
1381   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1382 
1383   NMethodIterator iter(NMethodIterator::not_unloading);
1384   while(iter.next()) {
1385     nmethod* nm = iter.method();
1386     if (nm->is_dependent_on_method(dependee)) {
1387       deopt_scope->mark(nm);
1388     }
1389   }
1390 }
1391 
1392 void CodeCache::make_marked_nmethods_deoptimized() {
1393   RelaxedNMethodIterator iter(RelaxedNMethodIterator::not_unloading);
1394   while(iter.next()) {
1395     nmethod* nm = iter.method();
1396     if (nm->is_marked_for_deoptimization() && !nm->has_been_deoptimized() && nm->can_be_deoptimized()) {
1397       nm->make_not_entrant(nmethod::InvalidationReason::MARKED_FOR_DEOPTIMIZATION);
1398       nm->make_deoptimized();
1399     }
1400   }
1401 }
1402 
1403 // Marks compiled methods dependent on dependee.
1404 void CodeCache::mark_dependents_on(DeoptimizationScope* deopt_scope, InstanceKlass* dependee) {
1405   assert_lock_strong(Compile_lock);
1406 
1407   if (!has_nmethods_with_dependencies()) {
1408     return;
1409   }
1410 
1411   if (dependee->is_linked()) {
1412     // Class initialization state change.
1413     KlassInitDepChange changes(dependee);
1414     mark_for_deoptimization(deopt_scope, changes);
1415   } else {
1416     // New class is loaded.
1417     NewKlassDepChange changes(dependee);
1418     mark_for_deoptimization(deopt_scope, changes);
1419   }
1420 }
1421 
1422 // Marks compiled methods dependent on dependee
1423 void CodeCache::mark_dependents_on_method_for_breakpoint(const methodHandle& m_h) {
1424   assert(SafepointSynchronize::is_at_safepoint(), "invariant");
1425 
1426   DeoptimizationScope deopt_scope;
1427   // Compute the dependent nmethods
1428   mark_for_deoptimization(&deopt_scope, m_h());
1429   deopt_scope.deoptimize_marked();
1430 }
1431 
1432 void CodeCache::verify() {
1433   assert_locked_or_safepoint(CodeCache_lock);
1434   FOR_ALL_HEAPS(heap) {
1435     (*heap)->verify();
1436     FOR_ALL_BLOBS(cb, *heap) {
1437       cb->verify();
1438     }
1439   }
1440 }
1441 
1442 // A CodeHeap is full. Print out warning and report event.
1443 PRAGMA_DIAG_PUSH
1444 PRAGMA_FORMAT_NONLITERAL_IGNORED
1445 void CodeCache::report_codemem_full(CodeBlobType code_blob_type, bool print) {
1446   // Get nmethod heap for the given CodeBlobType and build CodeCacheFull event
1447   CodeHeap* heap = get_code_heap(code_blob_type);
1448   assert(heap != nullptr, "heap is null");
1449 
1450   int full_count = heap->report_full();
1451 
1452   if ((full_count == 1) || print) {
1453     // Not yet reported for this heap, report
1454     if (SegmentedCodeCache) {
1455       ResourceMark rm;
1456       stringStream msg1_stream, msg2_stream;
1457       msg1_stream.print("%s is full. Compiler has been disabled.",
1458                         get_code_heap_name(code_blob_type));
1459       msg2_stream.print("Try increasing the code heap size using -XX:%s=",
1460                  get_code_heap_flag_name(code_blob_type));
1461       const char *msg1 = msg1_stream.as_string();
1462       const char *msg2 = msg2_stream.as_string();
1463 
1464       log_warning(codecache)("%s", msg1);
1465       log_warning(codecache)("%s", msg2);
1466       warning("%s", msg1);
1467       warning("%s", msg2);
1468     } else {
1469       const char *msg1 = "CodeCache is full. Compiler has been disabled.";
1470       const char *msg2 = "Try increasing the code cache size using -XX:ReservedCodeCacheSize=";
1471 
1472       log_warning(codecache)("%s", msg1);
1473       log_warning(codecache)("%s", msg2);
1474       warning("%s", msg1);
1475       warning("%s", msg2);
1476     }
1477     stringStream s;
1478     // Dump code cache into a buffer before locking the tty.
1479     {
1480       MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1481       print_summary(&s);
1482     }
1483     {
1484       ttyLocker ttyl;
1485       tty->print("%s", s.freeze());
1486     }
1487 
1488     if (full_count == 1) {
1489       if (PrintCodeHeapAnalytics) {
1490         CompileBroker::print_heapinfo(tty, "all", 4096); // details, may be a lot!
1491       }
1492     }
1493   }
1494 
1495   EventCodeCacheFull event;
1496   if (event.should_commit()) {
1497     event.set_codeBlobType((u1)code_blob_type);
1498     event.set_startAddress((u8)heap->low_boundary());
1499     event.set_commitedTopAddress((u8)heap->high());
1500     event.set_reservedTopAddress((u8)heap->high_boundary());
1501     event.set_entryCount(heap->blob_count());
1502     event.set_methodCount(heap->nmethod_count());
1503     event.set_adaptorCount(heap->adapter_count());
1504     event.set_unallocatedCapacity(heap->unallocated_capacity());
1505     event.set_fullCount(heap->full_count());
1506     event.set_codeCacheMaxCapacity(CodeCache::max_capacity());
1507     event.commit();
1508   }
1509 }
1510 PRAGMA_DIAG_POP
1511 
1512 void CodeCache::print_memory_overhead() {
1513   size_t wasted_bytes = 0;
1514   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1515       CodeHeap* curr_heap = *heap;
1516       for (CodeBlob* cb = (CodeBlob*)curr_heap->first(); cb != nullptr; cb = (CodeBlob*)curr_heap->next(cb)) {
1517         HeapBlock* heap_block = ((HeapBlock*)cb) - 1;
1518         wasted_bytes += heap_block->length() * CodeCacheSegmentSize - cb->size();
1519       }
1520   }
1521   // Print bytes that are allocated in the freelist
1522   ttyLocker ttl;
1523   tty->print_cr("Number of elements in freelist: %zd",       freelists_length());
1524   tty->print_cr("Allocated in freelist:          %zdkB",  bytes_allocated_in_freelists()/K);
1525   tty->print_cr("Unused bytes in CodeBlobs:      %zdkB",  (wasted_bytes/K));
1526   tty->print_cr("Segment map size:               %zdkB",  allocated_segments()/K); // 1 byte per segment
1527 }
1528 
1529 //------------------------------------------------------------------------------------------------
1530 // Non-product version
1531 
1532 #ifndef PRODUCT
1533 
1534 void CodeCache::print_trace(const char* event, CodeBlob* cb, uint size) {
1535   if (PrintCodeCache2) {  // Need to add a new flag
1536     ResourceMark rm;
1537     if (size == 0) {
1538       int s = cb->size();
1539       assert(s >= 0, "CodeBlob size is negative: %d", s);
1540       size = (uint) s;
1541     }
1542     tty->print_cr("CodeCache %s:  addr: " INTPTR_FORMAT ", size: 0x%x", event, p2i(cb), size);
1543   }
1544 }
1545 
1546 void CodeCache::print_internals() {
1547   int nmethodCount = 0;
1548   int runtimeStubCount = 0;
1549   int upcallStubCount = 0;
1550   int adapterCount = 0;
1551   int mhAdapterCount = 0;
1552   int vtableBlobCount = 0;
1553   int deoptimizationStubCount = 0;
1554   int uncommonTrapStubCount = 0;
1555   int exceptionStubCount = 0;
1556   int safepointStubCount = 0;
1557   int bufferBlobCount = 0;
1558   int total = 0;
1559   int nmethodNotEntrant = 0;
1560   int nmethodJava = 0;
1561   int nmethodNative = 0;
1562   int max_nm_size = 0;
1563   ResourceMark rm;
1564 
1565   int i = 0;
1566   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1567     if ((_nmethod_heaps->length() >= 1) && Verbose) {
1568       tty->print_cr("-- %s --", (*heap)->name());
1569     }
1570     FOR_ALL_BLOBS(cb, *heap) {
1571       total++;
1572       if (cb->is_nmethod()) {
1573         nmethod* nm = (nmethod*)cb;
1574 
1575         if (Verbose && nm->method() != nullptr) {
1576           ResourceMark rm;
1577           char *method_name = nm->method()->name_and_sig_as_C_string();
1578           tty->print("%s", method_name);
1579           if(nm->is_not_entrant()) { tty->print_cr(" not-entrant"); }
1580         }
1581 
1582         nmethodCount++;
1583 
1584         if(nm->is_not_entrant()) { nmethodNotEntrant++; }
1585         if(nm->method() != nullptr && nm->is_native_method()) { nmethodNative++; }
1586 
1587         if(nm->method() != nullptr && nm->is_java_method()) {
1588           nmethodJava++;
1589           max_nm_size = MAX2(max_nm_size, nm->size());
1590         }
1591       } else if (cb->is_runtime_stub()) {
1592         runtimeStubCount++;
1593       } else if (cb->is_upcall_stub()) {
1594         upcallStubCount++;
1595       } else if (cb->is_deoptimization_stub()) {
1596         deoptimizationStubCount++;
1597       } else if (cb->is_uncommon_trap_stub()) {
1598         uncommonTrapStubCount++;
1599       } else if (cb->is_exception_stub()) {
1600         exceptionStubCount++;
1601       } else if (cb->is_safepoint_stub()) {
1602         safepointStubCount++;
1603       } else if (cb->is_adapter_blob()) {
1604         adapterCount++;
1605       } else if (cb->is_method_handles_adapter_blob()) {
1606         mhAdapterCount++;
1607       } else if (cb->is_vtable_blob()) {
1608         vtableBlobCount++;
1609       } else if (cb->is_buffer_blob()) {
1610         bufferBlobCount++;
1611       }
1612     }
1613   }
1614 
1615   int bucketSize = 512;
1616   int bucketLimit = max_nm_size / bucketSize + 1;
1617   int *buckets = NEW_C_HEAP_ARRAY(int, bucketLimit, mtCode);
1618   memset(buckets, 0, sizeof(int) * bucketLimit);
1619 
1620   NMethodIterator iter(NMethodIterator::all);
1621   while(iter.next()) {
1622     nmethod* nm = iter.method();
1623     if(nm->method() != nullptr && nm->is_java_method()) {
1624       buckets[nm->size() / bucketSize]++;
1625     }
1626   }
1627 
1628   tty->print_cr("Code Cache Entries (total of %d)",total);
1629   tty->print_cr("-------------------------------------------------");
1630   tty->print_cr("nmethods: %d",nmethodCount);
1631   tty->print_cr("\tnot_entrant: %d",nmethodNotEntrant);
1632   tty->print_cr("\tjava: %d",nmethodJava);
1633   tty->print_cr("\tnative: %d",nmethodNative);
1634   tty->print_cr("runtime_stubs: %d",runtimeStubCount);
1635   tty->print_cr("upcall_stubs: %d",upcallStubCount);
1636   tty->print_cr("adapters: %d",adapterCount);
1637   tty->print_cr("MH adapters: %d",mhAdapterCount);
1638   tty->print_cr("VTables: %d",vtableBlobCount);
1639   tty->print_cr("buffer blobs: %d",bufferBlobCount);
1640   tty->print_cr("deoptimization_stubs: %d",deoptimizationStubCount);
1641   tty->print_cr("uncommon_traps: %d",uncommonTrapStubCount);
1642   tty->print_cr("exception_stubs: %d",exceptionStubCount);
1643   tty->print_cr("safepoint_stubs: %d",safepointStubCount);
1644   tty->print_cr("\nnmethod size distribution");
1645   tty->print_cr("-------------------------------------------------");
1646 
1647   for(int i=0; i<bucketLimit; i++) {
1648     if(buckets[i] != 0) {
1649       tty->print("%d - %d bytes",i*bucketSize,(i+1)*bucketSize);
1650       tty->fill_to(40);
1651       tty->print_cr("%d",buckets[i]);
1652     }
1653   }
1654 
1655   FREE_C_HEAP_ARRAY(int, buckets);
1656   print_memory_overhead();
1657 }
1658 
1659 #endif // !PRODUCT
1660 
1661 void CodeCache::print() {
1662   print_summary(tty);
1663 
1664 #ifndef PRODUCT
1665   if (!Verbose) return;
1666 
1667   CodeBlob_sizes live[CompLevel_full_optimization + 1];
1668   CodeBlob_sizes runtimeStub;
1669   CodeBlob_sizes upcallStub;
1670   CodeBlob_sizes uncommonTrapStub;
1671   CodeBlob_sizes deoptimizationStub;
1672   CodeBlob_sizes exceptionStub;
1673   CodeBlob_sizes safepointStub;
1674   CodeBlob_sizes adapter;
1675   CodeBlob_sizes mhAdapter;
1676   CodeBlob_sizes vtableBlob;
1677   CodeBlob_sizes bufferBlob;
1678   CodeBlob_sizes other;
1679 
1680   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1681     FOR_ALL_BLOBS(cb, *heap) {
1682       if (cb->is_nmethod()) {
1683         const int level = cb->as_nmethod()->comp_level();
1684         assert(0 <= level && level <= CompLevel_full_optimization, "Invalid compilation level");
1685         live[level].add(cb);
1686       } else if (cb->is_runtime_stub()) {
1687         runtimeStub.add(cb);
1688       } else if (cb->is_upcall_stub()) {
1689         upcallStub.add(cb);
1690       } else if (cb->is_deoptimization_stub()) {
1691         deoptimizationStub.add(cb);
1692       } else if (cb->is_uncommon_trap_stub()) {
1693         uncommonTrapStub.add(cb);
1694       } else if (cb->is_exception_stub()) {
1695         exceptionStub.add(cb);
1696       } else if (cb->is_safepoint_stub()) {
1697         safepointStub.add(cb);
1698       } else if (cb->is_adapter_blob()) {
1699         adapter.add(cb);
1700       } else if (cb->is_method_handles_adapter_blob()) {
1701         mhAdapter.add(cb);
1702       } else if (cb->is_vtable_blob()) {
1703         vtableBlob.add(cb);
1704       } else if (cb->is_buffer_blob()) {
1705         bufferBlob.add(cb);
1706       } else {
1707         other.add(cb);
1708       }
1709     }
1710   }
1711 
1712   tty->print_cr("nmethod dependency checking time %fs", dependentCheckTime.seconds());
1713 
1714   tty->print_cr("nmethod blobs per compilation level:");
1715   for (int i = 0; i <= CompLevel_full_optimization; i++) {
1716     const char *level_name;
1717     switch (i) {
1718     case CompLevel_none:              level_name = "none";              break;
1719     case CompLevel_simple:            level_name = "simple";            break;
1720     case CompLevel_limited_profile:   level_name = "limited profile";   break;
1721     case CompLevel_full_profile:      level_name = "full profile";      break;
1722     case CompLevel_full_optimization: level_name = "full optimization"; break;
1723     default: assert(false, "invalid compilation level");
1724     }
1725     tty->print_cr("%s:", level_name);
1726     live[i].print("live");
1727   }
1728 
1729   struct {
1730     const char* name;
1731     const CodeBlob_sizes* sizes;
1732   } non_nmethod_blobs[] = {
1733     { "runtime",        &runtimeStub },
1734     { "upcall",         &upcallStub },
1735     { "uncommon trap",  &uncommonTrapStub },
1736     { "deoptimization", &deoptimizationStub },
1737     { "exception",      &exceptionStub },
1738     { "safepoint",      &safepointStub },
1739     { "adapter",        &adapter },
1740     { "mh_adapter",     &mhAdapter },
1741     { "vtable",         &vtableBlob },
1742     { "buffer blob",    &bufferBlob },
1743     { "other",          &other },
1744   };
1745   tty->print_cr("Non-nmethod blobs:");
1746   for (auto& blob: non_nmethod_blobs) {
1747     blob.sizes->print(blob.name);
1748   }
1749 
1750   if (WizardMode) {
1751      // print the oop_map usage
1752     int code_size = 0;
1753     int number_of_blobs = 0;
1754     int number_of_oop_maps = 0;
1755     int map_size = 0;
1756     FOR_ALL_ALLOCABLE_HEAPS(heap) {
1757       FOR_ALL_BLOBS(cb, *heap) {
1758         number_of_blobs++;
1759         code_size += cb->code_size();
1760         ImmutableOopMapSet* set = cb->oop_maps();
1761         if (set != nullptr) {
1762           number_of_oop_maps += set->count();
1763           map_size           += set->nr_of_bytes();
1764         }
1765       }
1766     }
1767     tty->print_cr("OopMaps");
1768     tty->print_cr("  #blobs    = %d", number_of_blobs);
1769     tty->print_cr("  code size = %d", code_size);
1770     tty->print_cr("  #oop_maps = %d", number_of_oop_maps);
1771     tty->print_cr("  map size  = %d", map_size);
1772   }
1773 
1774 #endif // !PRODUCT
1775 }
1776 
1777 void CodeCache::print_summary(outputStream* st, bool detailed) {
1778   int full_count = 0;
1779   julong total_used = 0;
1780   julong total_max_used = 0;
1781   julong total_free = 0;
1782   julong total_size = 0;
1783   FOR_ALL_HEAPS(heap_iterator) {
1784     CodeHeap* heap = (*heap_iterator);
1785     size_t total = (heap->high_boundary() - heap->low_boundary());
1786     if (_heaps->length() >= 1) {
1787       st->print("%s:", heap->name());
1788     } else {
1789       st->print("CodeCache:");
1790     }
1791     size_t size = total/K;
1792     size_t used = (total - heap->unallocated_capacity())/K;
1793     size_t max_used = heap->max_allocated_capacity()/K;
1794     size_t free = heap->unallocated_capacity()/K;
1795     total_size += size;
1796     total_used += used;
1797     total_max_used += max_used;
1798     total_free += free;
1799     st->print_cr(" size=%zuKb used=%zu"
1800                  "Kb max_used=%zuKb free=%zuKb",
1801                  size, used, max_used, free);
1802 
1803     if (detailed) {
1804       st->print_cr(" bounds [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT "]",
1805                    p2i(heap->low_boundary()),
1806                    p2i(heap->high()),
1807                    p2i(heap->high_boundary()));
1808 
1809       full_count += get_codemem_full_count(heap->code_blob_type());
1810     }
1811   }
1812 
1813   if (detailed) {
1814     if (SegmentedCodeCache) {
1815       st->print("CodeCache:");
1816       st->print_cr(" size=" JULONG_FORMAT "Kb, used=" JULONG_FORMAT
1817                    "Kb, max_used=" JULONG_FORMAT "Kb, free=" JULONG_FORMAT "Kb",
1818                    total_size, total_used, total_max_used, total_free);
1819     }
1820     st->print_cr(" total_blobs=" UINT32_FORMAT ", nmethods=" UINT32_FORMAT
1821                  ", adapters=" UINT32_FORMAT ", full_count=" UINT32_FORMAT,
1822                  blob_count(), nmethod_count(), adapter_count(), full_count);
1823     st->print_cr("Compilation: %s, stopped_count=%d, restarted_count=%d",
1824                  CompileBroker::should_compile_new_jobs() ?
1825                  "enabled" : Arguments::mode() == Arguments::_int ?
1826                  "disabled (interpreter mode)" :
1827                  "disabled (not enough contiguous free space left)",
1828                  CompileBroker::get_total_compiler_stopped_count(),
1829                  CompileBroker::get_total_compiler_restarted_count());
1830   }
1831 }
1832 
1833 void CodeCache::print_codelist(outputStream* st) {
1834   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1835 
1836   NMethodIterator iter(NMethodIterator::not_unloading);
1837   while (iter.next()) {
1838     nmethod* nm = iter.method();
1839     ResourceMark rm;
1840     char* method_name = nm->method()->name_and_sig_as_C_string();
1841     const char* jvmci_name = nullptr;
1842 #if INCLUDE_JVMCI
1843     jvmci_name = nm->jvmci_name();
1844 #endif
1845     st->print_cr("%d %d %d %s%s%s [" INTPTR_FORMAT ", " INTPTR_FORMAT " - " INTPTR_FORMAT "]",
1846                  nm->compile_id(), nm->comp_level(), nm->get_state(),
1847                  method_name, jvmci_name ? " jvmci_name=" : "", jvmci_name ? jvmci_name : "",
1848                  (intptr_t)nm->header_begin(), (intptr_t)nm->code_begin(), (intptr_t)nm->code_end());
1849   }
1850 }
1851 
1852 void CodeCache::print_layout(outputStream* st) {
1853   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1854   ResourceMark rm;
1855   print_summary(st, true);
1856 }
1857 
1858 void CodeCache::log_state(outputStream* st) {
1859   st->print(" total_blobs='" UINT32_FORMAT "' nmethods='" UINT32_FORMAT "'"
1860             " adapters='" UINT32_FORMAT "' free_code_cache='%zu'",
1861             blob_count(), nmethod_count(), adapter_count(),
1862             unallocated_capacity());
1863 }
1864 
1865 #ifdef LINUX
1866 void CodeCache::write_perf_map(const char* filename, outputStream* st) {
1867   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1868   char fname[JVM_MAXPATHLEN];
1869   if (filename == nullptr) {
1870     // Invocation outside of jcmd requires pid substitution.
1871     if (!Arguments::copy_expand_pid(DEFAULT_PERFMAP_FILENAME,
1872                                     strlen(DEFAULT_PERFMAP_FILENAME),
1873                                     fname, JVM_MAXPATHLEN)) {
1874       st->print_cr("Warning: Not writing perf map as pid substitution failed.");
1875       return;
1876     }
1877     filename = fname;
1878   }
1879   fileStream fs(filename, "w");
1880   if (!fs.is_open()) {
1881     st->print_cr("Warning: Failed to create %s for perf map", filename);
1882     return;
1883   }
1884 
1885   AllCodeBlobsIterator iter(AllCodeBlobsIterator::not_unloading);
1886   while (iter.next()) {
1887     CodeBlob *cb = iter.method();
1888     ResourceMark rm;
1889     const char* method_name = nullptr;
1890     const char* jvmci_name = nullptr;
1891     if (cb->is_nmethod()) {
1892       nmethod* nm = cb->as_nmethod();
1893       method_name = nm->method()->external_name();
1894 #if INCLUDE_JVMCI
1895       jvmci_name = nm->jvmci_name();
1896 #endif
1897     } else {
1898       method_name = cb->name();
1899     }
1900     fs.print_cr(INTPTR_FORMAT " " INTPTR_FORMAT " %s%s%s",
1901                 (intptr_t)cb->code_begin(), (intptr_t)cb->code_size(),
1902                 method_name, jvmci_name ? " jvmci_name=" : "", jvmci_name ? jvmci_name : "");
1903   }
1904 }
1905 #endif // LINUX
1906 
1907 //---<  BEGIN  >--- CodeHeap State Analytics.
1908 
1909 void CodeCache::aggregate(outputStream *out, size_t granularity) {
1910   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1911     CodeHeapState::aggregate(out, (*heap), granularity);
1912   }
1913 }
1914 
1915 void CodeCache::discard(outputStream *out) {
1916   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1917     CodeHeapState::discard(out, (*heap));
1918   }
1919 }
1920 
1921 void CodeCache::print_usedSpace(outputStream *out) {
1922   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1923     CodeHeapState::print_usedSpace(out, (*heap));
1924   }
1925 }
1926 
1927 void CodeCache::print_freeSpace(outputStream *out) {
1928   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1929     CodeHeapState::print_freeSpace(out, (*heap));
1930   }
1931 }
1932 
1933 void CodeCache::print_count(outputStream *out) {
1934   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1935     CodeHeapState::print_count(out, (*heap));
1936   }
1937 }
1938 
1939 void CodeCache::print_space(outputStream *out) {
1940   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1941     CodeHeapState::print_space(out, (*heap));
1942   }
1943 }
1944 
1945 void CodeCache::print_age(outputStream *out) {
1946   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1947     CodeHeapState::print_age(out, (*heap));
1948   }
1949 }
1950 
1951 void CodeCache::print_names(outputStream *out) {
1952   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1953     CodeHeapState::print_names(out, (*heap));
1954   }
1955 }
1956 //---<  END  >--- CodeHeap State Analytics.