1 /*
   2  * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm_io.h"
  27 #include "code/codeBlob.hpp"
  28 #include "code/codeCache.hpp"
  29 #include "code/codeHeapState.hpp"
  30 #include "code/compiledIC.hpp"
  31 #include "code/dependencies.hpp"
  32 #include "code/dependencyContext.hpp"
  33 #include "code/icBuffer.hpp"
  34 #include "code/nmethod.hpp"
  35 #include "code/pcDesc.hpp"
  36 #include "compiler/compilationPolicy.hpp"
  37 #include "compiler/compileBroker.hpp"
  38 #include "compiler/oopMap.hpp"
  39 #include "gc/shared/collectedHeap.hpp"
  40 #include "jfr/jfrEvents.hpp"
  41 #include "logging/log.hpp"
  42 #include "logging/logStream.hpp"
  43 #include "memory/allocation.inline.hpp"
  44 #include "memory/iterator.hpp"
  45 #include "memory/resourceArea.hpp"
  46 #include "memory/universe.hpp"
  47 #include "oops/method.inline.hpp"
  48 #include "oops/objArrayOop.hpp"
  49 #include "oops/oop.inline.hpp"
  50 #include "oops/verifyOopClosure.hpp"
  51 #include "runtime/arguments.hpp"
  52 #include "runtime/atomic.hpp"
  53 #include "runtime/deoptimization.hpp"
  54 #include "runtime/globals_extension.hpp"
  55 #include "runtime/handles.inline.hpp"
  56 #include "runtime/icache.hpp"
  57 #include "runtime/java.hpp"
  58 #include "runtime/mutexLocker.hpp"
  59 #include "runtime/safepointVerifiers.hpp"
  60 #include "runtime/sweeper.hpp"
  61 #include "runtime/vmThread.hpp"
  62 #include "services/memoryService.hpp"
  63 #include "utilities/align.hpp"
  64 #include "utilities/vmError.hpp"
  65 #include "utilities/xmlstream.hpp"
  66 #ifdef COMPILER1
  67 #include "c1/c1_Compilation.hpp"
  68 #include "c1/c1_Compiler.hpp"
  69 #endif
  70 #ifdef COMPILER2
  71 #include "opto/c2compiler.hpp"
  72 #include "opto/compile.hpp"
  73 #include "opto/node.hpp"
  74 #endif
  75 
  76 // Helper class for printing in CodeCache
  77 class CodeBlob_sizes {
  78  private:
  79   int count;
  80   int total_size;
  81   int header_size;
  82   int code_size;
  83   int stub_size;
  84   int relocation_size;
  85   int scopes_oop_size;
  86   int scopes_metadata_size;
  87   int scopes_data_size;
  88   int scopes_pcs_size;
  89 
  90  public:
  91   CodeBlob_sizes() {
  92     count            = 0;
  93     total_size       = 0;
  94     header_size      = 0;
  95     code_size        = 0;
  96     stub_size        = 0;
  97     relocation_size  = 0;
  98     scopes_oop_size  = 0;
  99     scopes_metadata_size  = 0;
 100     scopes_data_size = 0;
 101     scopes_pcs_size  = 0;
 102   }
 103 
 104   int total()                                    { return total_size; }
 105   bool is_empty()                                { return count == 0; }
 106 
 107   void print(const char* title) {
 108     tty->print_cr(" #%d %s = %dK (hdr %d%%,  loc %d%%, code %d%%, stub %d%%, [oops %d%%, metadata %d%%, data %d%%, pcs %d%%])",
 109                   count,
 110                   title,
 111                   (int)(total() / K),
 112                   header_size             * 100 / total_size,
 113                   relocation_size         * 100 / total_size,
 114                   code_size               * 100 / total_size,
 115                   stub_size               * 100 / total_size,
 116                   scopes_oop_size         * 100 / total_size,
 117                   scopes_metadata_size    * 100 / total_size,
 118                   scopes_data_size        * 100 / total_size,
 119                   scopes_pcs_size         * 100 / total_size);
 120   }
 121 
 122   void add(CodeBlob* cb) {
 123     count++;
 124     total_size       += cb->size();
 125     header_size      += cb->header_size();
 126     relocation_size  += cb->relocation_size();
 127     if (cb->is_nmethod()) {
 128       nmethod* nm = cb->as_nmethod_or_null();
 129       code_size        += nm->insts_size();
 130       stub_size        += nm->stub_size();
 131 
 132       scopes_oop_size  += nm->oops_size();
 133       scopes_metadata_size  += nm->metadata_size();
 134       scopes_data_size += nm->scopes_data_size();
 135       scopes_pcs_size  += nm->scopes_pcs_size();
 136     } else {
 137       code_size        += cb->code_size();
 138     }
 139   }
 140 };
 141 
 142 // Iterate over all CodeHeaps
 143 #define FOR_ALL_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _heaps->begin(); heap != _heaps->end(); ++heap)
 144 #define FOR_ALL_NMETHOD_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _nmethod_heaps->begin(); heap != _nmethod_heaps->end(); ++heap)
 145 #define FOR_ALL_ALLOCABLE_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _allocable_heaps->begin(); heap != _allocable_heaps->end(); ++heap)
 146 
 147 // Iterate over all CodeBlobs (cb) on the given CodeHeap
 148 #define FOR_ALL_BLOBS(cb, heap) for (CodeBlob* cb = first_blob(heap); cb != NULL; cb = next_blob(heap, cb))
 149 
 150 address CodeCache::_low_bound = 0;
 151 address CodeCache::_high_bound = 0;
 152 int CodeCache::_number_of_nmethods_with_dependencies = 0;
 153 ExceptionCache* volatile CodeCache::_exception_cache_purge_list = NULL;
 154 
 155 // Initialize arrays of CodeHeap subsets
 156 GrowableArray<CodeHeap*>* CodeCache::_heaps = new(ResourceObj::C_HEAP, mtCode) GrowableArray<CodeHeap*> (CodeBlobType::All, mtCode);
 157 GrowableArray<CodeHeap*>* CodeCache::_compiled_heaps = new(ResourceObj::C_HEAP, mtCode) GrowableArray<CodeHeap*> (CodeBlobType::All, mtCode);
 158 GrowableArray<CodeHeap*>* CodeCache::_nmethod_heaps = new(ResourceObj::C_HEAP, mtCode) GrowableArray<CodeHeap*> (CodeBlobType::All, mtCode);
 159 GrowableArray<CodeHeap*>* CodeCache::_allocable_heaps = new(ResourceObj::C_HEAP, mtCode) GrowableArray<CodeHeap*> (CodeBlobType::All, mtCode);
 160 
 161 void CodeCache::check_heap_sizes(size_t non_nmethod_size, size_t profiled_size, size_t non_profiled_size, size_t cache_size, bool all_set) {
 162   size_t total_size = non_nmethod_size + profiled_size + non_profiled_size;
 163   // Prepare error message
 164   const char* error = "Invalid code heap sizes";
 165   err_msg message("NonNMethodCodeHeapSize (" SIZE_FORMAT "K) + ProfiledCodeHeapSize (" SIZE_FORMAT "K)"
 166                   " + NonProfiledCodeHeapSize (" SIZE_FORMAT "K) = " SIZE_FORMAT "K",
 167           non_nmethod_size/K, profiled_size/K, non_profiled_size/K, total_size/K);
 168 
 169   if (total_size > cache_size) {
 170     // Some code heap sizes were explicitly set: total_size must be <= cache_size
 171     message.append(" is greater than ReservedCodeCacheSize (" SIZE_FORMAT "K).", cache_size/K);
 172     vm_exit_during_initialization(error, message);
 173   } else if (all_set && total_size != cache_size) {
 174     // All code heap sizes were explicitly set: total_size must equal cache_size
 175     message.append(" is not equal to ReservedCodeCacheSize (" SIZE_FORMAT "K).", cache_size/K);
 176     vm_exit_during_initialization(error, message);
 177   }
 178 }
 179 
 180 void CodeCache::initialize_heaps() {
 181   bool non_nmethod_set      = FLAG_IS_CMDLINE(NonNMethodCodeHeapSize);
 182   bool profiled_set         = FLAG_IS_CMDLINE(ProfiledCodeHeapSize);
 183   bool non_profiled_set     = FLAG_IS_CMDLINE(NonProfiledCodeHeapSize);
 184   size_t min_size           = os::vm_page_size();
 185   size_t cache_size         = ReservedCodeCacheSize;
 186   size_t non_nmethod_size   = NonNMethodCodeHeapSize;
 187   size_t profiled_size      = ProfiledCodeHeapSize;
 188   size_t non_profiled_size  = NonProfiledCodeHeapSize;
 189   // Check if total size set via command line flags exceeds the reserved size
 190   check_heap_sizes((non_nmethod_set  ? non_nmethod_size  : min_size),
 191                    (profiled_set     ? profiled_size     : min_size),
 192                    (non_profiled_set ? non_profiled_size : min_size),
 193                    cache_size,
 194                    non_nmethod_set && profiled_set && non_profiled_set);
 195 
 196   // Determine size of compiler buffers
 197   size_t code_buffers_size = 0;
 198 #ifdef COMPILER1
 199   // C1 temporary code buffers (see Compiler::init_buffer_blob())
 200   const int c1_count = CompilationPolicy::c1_count();
 201   code_buffers_size += c1_count * Compiler::code_buffer_size();
 202 #endif
 203 #ifdef COMPILER2
 204   // C2 scratch buffers (see Compile::init_scratch_buffer_blob())
 205   const int c2_count = CompilationPolicy::c2_count();
 206   // Initial size of constant table (this may be increased if a compiled method needs more space)
 207   code_buffers_size += c2_count * C2Compiler::initial_code_buffer_size();
 208 #endif
 209 
 210   // Increase default non_nmethod_size to account for compiler buffers
 211   if (!non_nmethod_set) {
 212     non_nmethod_size += code_buffers_size;
 213   }
 214   // Calculate default CodeHeap sizes if not set by user
 215   if (!non_nmethod_set && !profiled_set && !non_profiled_set) {
 216     // Check if we have enough space for the non-nmethod code heap
 217     if (cache_size > non_nmethod_size) {
 218       // Use the default value for non_nmethod_size and one half of the
 219       // remaining size for non-profiled and one half for profiled methods
 220       size_t remaining_size = cache_size - non_nmethod_size;
 221       profiled_size = remaining_size / 2;
 222       non_profiled_size = remaining_size - profiled_size;
 223     } else {
 224       // Use all space for the non-nmethod heap and set other heaps to minimal size
 225       non_nmethod_size = cache_size - 2 * min_size;
 226       profiled_size = min_size;
 227       non_profiled_size = min_size;
 228     }
 229   } else if (!non_nmethod_set || !profiled_set || !non_profiled_set) {
 230     // The user explicitly set some code heap sizes. Increase or decrease the (default)
 231     // sizes of the other code heaps accordingly. First adapt non-profiled and profiled
 232     // code heap sizes and then only change non-nmethod code heap size if still necessary.
 233     intx diff_size = cache_size - (non_nmethod_size + profiled_size + non_profiled_size);
 234     if (non_profiled_set) {
 235       if (!profiled_set) {
 236         // Adapt size of profiled code heap
 237         if (diff_size < 0 && ((intx)profiled_size + diff_size) <= 0) {
 238           // Not enough space available, set to minimum size
 239           diff_size += profiled_size - min_size;
 240           profiled_size = min_size;
 241         } else {
 242           profiled_size += diff_size;
 243           diff_size = 0;
 244         }
 245       }
 246     } else if (profiled_set) {
 247       // Adapt size of non-profiled code heap
 248       if (diff_size < 0 && ((intx)non_profiled_size + diff_size) <= 0) {
 249         // Not enough space available, set to minimum size
 250         diff_size += non_profiled_size - min_size;
 251         non_profiled_size = min_size;
 252       } else {
 253         non_profiled_size += diff_size;
 254         diff_size = 0;
 255       }
 256     } else if (non_nmethod_set) {
 257       // Distribute remaining size between profiled and non-profiled code heaps
 258       diff_size = cache_size - non_nmethod_size;
 259       profiled_size = diff_size / 2;
 260       non_profiled_size = diff_size - profiled_size;
 261       diff_size = 0;
 262     }
 263     if (diff_size != 0) {
 264       // Use non-nmethod code heap for remaining space requirements
 265       assert(!non_nmethod_set && ((intx)non_nmethod_size + diff_size) > 0, "sanity");
 266       non_nmethod_size += diff_size;
 267     }
 268   }
 269 
 270   // We do not need the profiled CodeHeap, use all space for the non-profiled CodeHeap
 271   if (!heap_available(CodeBlobType::MethodProfiled)) {
 272     non_profiled_size += profiled_size;
 273     profiled_size = 0;
 274   }
 275   // We do not need the non-profiled CodeHeap, use all space for the non-nmethod CodeHeap
 276   if (!heap_available(CodeBlobType::MethodNonProfiled)) {
 277     non_nmethod_size += non_profiled_size;
 278     non_profiled_size = 0;
 279   }
 280   // Make sure we have enough space for VM internal code
 281   uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3);
 282   if (non_nmethod_size < min_code_cache_size) {
 283     vm_exit_during_initialization(err_msg(
 284         "Not enough space in non-nmethod code heap to run VM: " SIZE_FORMAT "K < " SIZE_FORMAT "K",
 285         non_nmethod_size/K, min_code_cache_size/K));
 286   }
 287 
 288   // Verify sizes and update flag values
 289   assert(non_profiled_size + profiled_size + non_nmethod_size == cache_size, "Invalid code heap sizes");
 290   FLAG_SET_ERGO(NonNMethodCodeHeapSize, non_nmethod_size);
 291   FLAG_SET_ERGO(ProfiledCodeHeapSize, profiled_size);
 292   FLAG_SET_ERGO(NonProfiledCodeHeapSize, non_profiled_size);
 293 
 294   // If large page support is enabled, align code heaps according to large
 295   // page size to make sure that code cache is covered by large pages.
 296   const size_t alignment = MAX2(page_size(false, 8), (size_t) os::vm_allocation_granularity());
 297   non_nmethod_size = align_up(non_nmethod_size, alignment);
 298   profiled_size    = align_down(profiled_size, alignment);
 299 
 300   // Reserve one continuous chunk of memory for CodeHeaps and split it into
 301   // parts for the individual heaps. The memory layout looks like this:
 302   // ---------- high -----------
 303   //    Non-profiled nmethods
 304   //      Profiled nmethods
 305   //         Non-nmethods
 306   // ---------- low ------------
 307   ReservedCodeSpace rs = reserve_heap_memory(cache_size);
 308   ReservedSpace non_method_space    = rs.first_part(non_nmethod_size);
 309   ReservedSpace rest                = rs.last_part(non_nmethod_size);
 310   ReservedSpace profiled_space      = rest.first_part(profiled_size);
 311   ReservedSpace non_profiled_space  = rest.last_part(profiled_size);
 312 
 313   // Non-nmethods (stubs, adapters, ...)
 314   add_heap(non_method_space, "CodeHeap 'non-nmethods'", CodeBlobType::NonNMethod);
 315   // Tier 2 and tier 3 (profiled) methods
 316   add_heap(profiled_space, "CodeHeap 'profiled nmethods'", CodeBlobType::MethodProfiled);
 317   // Tier 1 and tier 4 (non-profiled) methods and native methods
 318   add_heap(non_profiled_space, "CodeHeap 'non-profiled nmethods'", CodeBlobType::MethodNonProfiled);
 319 }
 320 
 321 size_t CodeCache::page_size(bool aligned, size_t min_pages) {
 322   if (os::can_execute_large_page_memory()) {
 323     if (InitialCodeCacheSize < ReservedCodeCacheSize) {
 324       // Make sure that the page size allows for an incremental commit of the reserved space
 325       min_pages = MAX2(min_pages, (size_t)8);
 326     }
 327     return aligned ? os::page_size_for_region_aligned(ReservedCodeCacheSize, min_pages) :
 328                      os::page_size_for_region_unaligned(ReservedCodeCacheSize, min_pages);
 329   } else {
 330     return os::vm_page_size();
 331   }
 332 }
 333 
 334 ReservedCodeSpace CodeCache::reserve_heap_memory(size_t size) {
 335   // Align and reserve space for code cache
 336   const size_t rs_ps = page_size();
 337   const size_t rs_align = MAX2(rs_ps, (size_t) os::vm_allocation_granularity());
 338   const size_t rs_size = align_up(size, rs_align);
 339   ReservedCodeSpace rs(rs_size, rs_align, rs_ps);
 340   if (!rs.is_reserved()) {
 341     vm_exit_during_initialization(err_msg("Could not reserve enough space for code cache (" SIZE_FORMAT "K)",
 342                                           rs_size/K));
 343   }
 344 
 345   // Initialize bounds
 346   _low_bound = (address)rs.base();
 347   _high_bound = _low_bound + rs.size();
 348   return rs;
 349 }
 350 
 351 // Heaps available for allocation
 352 bool CodeCache::heap_available(int code_blob_type) {
 353   if (!SegmentedCodeCache) {
 354     // No segmentation: use a single code heap
 355     return (code_blob_type == CodeBlobType::All);
 356   } else if (Arguments::is_interpreter_only()) {
 357     // Interpreter only: we don't need any method code heaps
 358     return (code_blob_type == CodeBlobType::NonNMethod);
 359   } else if (CompilerConfig::is_c1_profiling()) {
 360     // Tiered compilation: use all code heaps
 361     return (code_blob_type < CodeBlobType::All);
 362   } else {
 363     // No TieredCompilation: we only need the non-nmethod and non-profiled code heap
 364     return (code_blob_type == CodeBlobType::NonNMethod) ||
 365            (code_blob_type == CodeBlobType::MethodNonProfiled);
 366   }
 367 }
 368 
 369 const char* CodeCache::get_code_heap_flag_name(int code_blob_type) {
 370   switch(code_blob_type) {
 371   case CodeBlobType::NonNMethod:
 372     return "NonNMethodCodeHeapSize";
 373     break;
 374   case CodeBlobType::MethodNonProfiled:
 375     return "NonProfiledCodeHeapSize";
 376     break;
 377   case CodeBlobType::MethodProfiled:
 378     return "ProfiledCodeHeapSize";
 379     break;
 380   }
 381   ShouldNotReachHere();
 382   return NULL;
 383 }
 384 
 385 int CodeCache::code_heap_compare(CodeHeap* const &lhs, CodeHeap* const &rhs) {
 386   if (lhs->code_blob_type() == rhs->code_blob_type()) {
 387     return (lhs > rhs) ? 1 : ((lhs < rhs) ? -1 : 0);
 388   } else {
 389     return lhs->code_blob_type() - rhs->code_blob_type();
 390   }
 391 }
 392 
 393 void CodeCache::add_heap(CodeHeap* heap) {
 394   assert(!Universe::is_fully_initialized(), "late heap addition?");
 395 
 396   _heaps->insert_sorted<code_heap_compare>(heap);
 397 
 398   int type = heap->code_blob_type();
 399   if (code_blob_type_accepts_compiled(type)) {
 400     _compiled_heaps->insert_sorted<code_heap_compare>(heap);
 401   }
 402   if (code_blob_type_accepts_nmethod(type)) {
 403     _nmethod_heaps->insert_sorted<code_heap_compare>(heap);
 404   }
 405   if (code_blob_type_accepts_allocable(type)) {
 406     _allocable_heaps->insert_sorted<code_heap_compare>(heap);
 407   }
 408 }
 409 
 410 void CodeCache::add_heap(ReservedSpace rs, const char* name, int code_blob_type) {
 411   // Check if heap is needed
 412   if (!heap_available(code_blob_type)) {
 413     return;
 414   }
 415 
 416   // Create CodeHeap
 417   CodeHeap* heap = new CodeHeap(name, code_blob_type);
 418   add_heap(heap);
 419 
 420   // Reserve Space
 421   size_t size_initial = MIN2((size_t)InitialCodeCacheSize, rs.size());
 422   size_initial = align_up(size_initial, os::vm_page_size());
 423   if (!heap->reserve(rs, size_initial, CodeCacheSegmentSize)) {
 424     vm_exit_during_initialization(err_msg("Could not reserve enough space in %s (" SIZE_FORMAT "K)",
 425                                           heap->name(), size_initial/K));
 426   }
 427 
 428   // Register the CodeHeap
 429   MemoryService::add_code_heap_memory_pool(heap, name);
 430 }
 431 
 432 CodeHeap* CodeCache::get_code_heap_containing(void* start) {
 433   FOR_ALL_HEAPS(heap) {
 434     if ((*heap)->contains(start)) {
 435       return *heap;
 436     }
 437   }
 438   return NULL;
 439 }
 440 
 441 CodeHeap* CodeCache::get_code_heap(const CodeBlob* cb) {
 442   assert(cb != NULL, "CodeBlob is null");
 443   FOR_ALL_HEAPS(heap) {
 444     if ((*heap)->contains_blob(cb)) {
 445       return *heap;
 446     }
 447   }
 448   ShouldNotReachHere();
 449   return NULL;
 450 }
 451 
 452 CodeHeap* CodeCache::get_code_heap(int code_blob_type) {
 453   FOR_ALL_HEAPS(heap) {
 454     if ((*heap)->accepts(code_blob_type)) {
 455       return *heap;
 456     }
 457   }
 458   return NULL;
 459 }
 460 
 461 CodeBlob* CodeCache::first_blob(CodeHeap* heap) {
 462   assert_locked_or_safepoint(CodeCache_lock);
 463   assert(heap != NULL, "heap is null");
 464   return (CodeBlob*)heap->first();
 465 }
 466 
 467 CodeBlob* CodeCache::first_blob(int code_blob_type) {
 468   if (heap_available(code_blob_type)) {
 469     return first_blob(get_code_heap(code_blob_type));
 470   } else {
 471     return NULL;
 472   }
 473 }
 474 
 475 CodeBlob* CodeCache::next_blob(CodeHeap* heap, CodeBlob* cb) {
 476   assert_locked_or_safepoint(CodeCache_lock);
 477   assert(heap != NULL, "heap is null");
 478   return (CodeBlob*)heap->next(cb);
 479 }
 480 
 481 /**
 482  * Do not seize the CodeCache lock here--if the caller has not
 483  * already done so, we are going to lose bigtime, since the code
 484  * cache will contain a garbage CodeBlob until the caller can
 485  * run the constructor for the CodeBlob subclass he is busy
 486  * instantiating.
 487  */
 488 CodeBlob* CodeCache::allocate(int size, int code_blob_type, bool handle_alloc_failure, int orig_code_blob_type) {
 489   // Possibly wakes up the sweeper thread.
 490   NMethodSweeper::report_allocation(code_blob_type);
 491   assert_locked_or_safepoint(CodeCache_lock);
 492   assert(size > 0, "Code cache allocation request must be > 0 but is %d", size);
 493   if (size <= 0) {
 494     return NULL;
 495   }
 496   CodeBlob* cb = NULL;
 497 
 498   // Get CodeHeap for the given CodeBlobType
 499   CodeHeap* heap = get_code_heap(code_blob_type);
 500   assert(heap != NULL, "heap is null");
 501 
 502   while (true) {
 503     cb = (CodeBlob*)heap->allocate(size);
 504     if (cb != NULL) break;
 505     if (!heap->expand_by(CodeCacheExpansionSize)) {
 506       // Save original type for error reporting
 507       if (orig_code_blob_type == CodeBlobType::All) {
 508         orig_code_blob_type = code_blob_type;
 509       }
 510       // Expansion failed
 511       if (SegmentedCodeCache) {
 512         // Fallback solution: Try to store code in another code heap.
 513         // NonNMethod -> MethodNonProfiled -> MethodProfiled (-> MethodNonProfiled)
 514         // Note that in the sweeper, we check the reverse_free_ratio of the code heap
 515         // and force stack scanning if less than 10% of the code heap are free.
 516         int type = code_blob_type;
 517         switch (type) {
 518         case CodeBlobType::NonNMethod:
 519           type = CodeBlobType::MethodNonProfiled;
 520           break;
 521         case CodeBlobType::MethodNonProfiled:
 522           type = CodeBlobType::MethodProfiled;
 523           break;
 524         case CodeBlobType::MethodProfiled:
 525           // Avoid loop if we already tried that code heap
 526           if (type == orig_code_blob_type) {
 527             type = CodeBlobType::MethodNonProfiled;
 528           }
 529           break;
 530         }
 531         if (type != code_blob_type && type != orig_code_blob_type && heap_available(type)) {
 532           if (PrintCodeCacheExtension) {
 533             tty->print_cr("Extension of %s failed. Trying to allocate in %s.",
 534                           heap->name(), get_code_heap(type)->name());
 535           }
 536           return allocate(size, type, handle_alloc_failure, orig_code_blob_type);
 537         }
 538       }
 539       if (handle_alloc_failure) {
 540         MutexUnlocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 541         CompileBroker::handle_full_code_cache(orig_code_blob_type);
 542       }
 543       return NULL;
 544     }
 545     if (PrintCodeCacheExtension) {
 546       ResourceMark rm;
 547       if (_nmethod_heaps->length() >= 1) {
 548         tty->print("%s", heap->name());
 549       } else {
 550         tty->print("CodeCache");
 551       }
 552       tty->print_cr(" extended to [" INTPTR_FORMAT ", " INTPTR_FORMAT "] (" SSIZE_FORMAT " bytes)",
 553                     (intptr_t)heap->low_boundary(), (intptr_t)heap->high(),
 554                     (address)heap->high() - (address)heap->low_boundary());
 555     }
 556   }
 557   print_trace("allocation", cb, size);
 558   return cb;
 559 }
 560 
 561 void CodeCache::free(CodeBlob* cb) {
 562   assert_locked_or_safepoint(CodeCache_lock);
 563   CodeHeap* heap = get_code_heap(cb);
 564   print_trace("free", cb);
 565   if (cb->is_nmethod()) {
 566     heap->set_nmethod_count(heap->nmethod_count() - 1);
 567     if (((nmethod *)cb)->has_dependencies()) {
 568       _number_of_nmethods_with_dependencies--;
 569     }
 570   }
 571   if (cb->is_adapter_blob()) {
 572     heap->set_adapter_count(heap->adapter_count() - 1);
 573   }
 574 
 575   // Get heap for given CodeBlob and deallocate
 576   get_code_heap(cb)->deallocate(cb);
 577 
 578   assert(heap->blob_count() >= 0, "sanity check");
 579 }
 580 
 581 void CodeCache::free_unused_tail(CodeBlob* cb, size_t used) {
 582   assert_locked_or_safepoint(CodeCache_lock);
 583   guarantee(cb->is_buffer_blob() && strncmp("Interpreter", cb->name(), 11) == 0, "Only possible for interpreter!");
 584   print_trace("free_unused_tail", cb);
 585 
 586   // We also have to account for the extra space (i.e. header) used by the CodeBlob
 587   // which provides the memory (see BufferBlob::create() in codeBlob.cpp).
 588   used += CodeBlob::align_code_offset(cb->header_size());
 589 
 590   // Get heap for given CodeBlob and deallocate its unused tail
 591   get_code_heap(cb)->deallocate_tail(cb, used);
 592   // Adjust the sizes of the CodeBlob
 593   cb->adjust_size(used);
 594 }
 595 
 596 void CodeCache::commit(CodeBlob* cb) {
 597   // this is called by nmethod::nmethod, which must already own CodeCache_lock
 598   assert_locked_or_safepoint(CodeCache_lock);
 599   CodeHeap* heap = get_code_heap(cb);
 600   if (cb->is_nmethod()) {
 601     heap->set_nmethod_count(heap->nmethod_count() + 1);
 602     if (((nmethod *)cb)->has_dependencies()) {
 603       _number_of_nmethods_with_dependencies++;
 604     }
 605   }
 606   if (cb->is_adapter_blob()) {
 607     heap->set_adapter_count(heap->adapter_count() + 1);
 608   }
 609 
 610   // flush the hardware I-cache
 611   ICache::invalidate_range(cb->content_begin(), cb->content_size());
 612 }
 613 
 614 bool CodeCache::contains(void *p) {
 615   // S390 uses contains() in current_frame(), which is used before
 616   // code cache initialization if NativeMemoryTracking=detail is set.
 617   S390_ONLY(if (_heaps == NULL) return false;)
 618   // It should be ok to call contains without holding a lock.
 619   FOR_ALL_HEAPS(heap) {
 620     if ((*heap)->contains(p)) {
 621       return true;
 622     }
 623   }
 624   return false;
 625 }
 626 
 627 bool CodeCache::contains(nmethod *nm) {
 628   return contains((void *)nm);
 629 }
 630 
 631 // This method is safe to call without holding the CodeCache_lock, as long as a dead CodeBlob is not
 632 // looked up (i.e., one that has been marked for deletion). It only depends on the _segmap to contain
 633 // valid indices, which it will always do, as long as the CodeBlob is not in the process of being recycled.
 634 CodeBlob* CodeCache::find_blob(void* start) {
 635   CodeBlob* result = find_blob_unsafe(start);
 636   // We could potentially look up non_entrant methods
 637   guarantee(result == NULL || !result->is_zombie() || result->is_locked_by_vm() || VMError::is_error_reported(), "unsafe access to zombie method");
 638   return result;
 639 }
 640 
 641 // Lookup that does not fail if you lookup a zombie method (if you call this, be sure to know
 642 // what you are doing)
 643 CodeBlob* CodeCache::find_blob_unsafe(void* start) {
 644   // NMT can walk the stack before code cache is created
 645   if (_heaps != NULL) {
 646     CodeHeap* heap = get_code_heap_containing(start);
 647     if (heap != NULL) {
 648       return heap->find_blob_unsafe(start);
 649     }
 650   }
 651   return NULL;
 652 }
 653 
 654 nmethod* CodeCache::find_nmethod(void* start) {
 655   CodeBlob* cb = find_blob(start);
 656   assert(cb->is_nmethod(), "did not find an nmethod");
 657   return (nmethod*)cb;
 658 }
 659 
 660 void CodeCache::blobs_do(void f(CodeBlob* nm)) {
 661   assert_locked_or_safepoint(CodeCache_lock);
 662   FOR_ALL_HEAPS(heap) {
 663     FOR_ALL_BLOBS(cb, *heap) {
 664       f(cb);
 665     }
 666   }
 667 }
 668 
 669 void CodeCache::nmethods_do(void f(nmethod* nm)) {
 670   assert_locked_or_safepoint(CodeCache_lock);
 671   NMethodIterator iter(NMethodIterator::all_blobs);
 672   while(iter.next()) {
 673     f(iter.method());
 674   }
 675 }
 676 
 677 void CodeCache::metadata_do(MetadataClosure* f) {
 678   assert_locked_or_safepoint(CodeCache_lock);
 679   NMethodIterator iter(NMethodIterator::only_alive_and_not_unloading);
 680   while(iter.next()) {
 681     iter.method()->metadata_do(f);
 682   }
 683 }
 684 
 685 int CodeCache::alignment_unit() {
 686   return (int)_heaps->first()->alignment_unit();
 687 }
 688 
 689 int CodeCache::alignment_offset() {
 690   return (int)_heaps->first()->alignment_offset();
 691 }
 692 
 693 // Mark nmethods for unloading if they contain otherwise unreachable oops.
 694 void CodeCache::do_unloading(BoolObjectClosure* is_alive, bool unloading_occurred) {
 695   assert_locked_or_safepoint(CodeCache_lock);
 696   UnloadingScope scope(is_alive);
 697   CompiledMethodIterator iter(CompiledMethodIterator::only_alive);
 698   while(iter.next()) {
 699     iter.method()->do_unloading(unloading_occurred);
 700   }
 701 }
 702 
 703 void CodeCache::blobs_do(CodeBlobClosure* f) {
 704   assert_locked_or_safepoint(CodeCache_lock);
 705   FOR_ALL_ALLOCABLE_HEAPS(heap) {
 706     FOR_ALL_BLOBS(cb, *heap) {
 707       if (cb->is_alive()) {
 708         f->do_code_blob(cb);
 709 #ifdef ASSERT
 710         if (cb->is_nmethod()) {
 711           Universe::heap()->verify_nmethod((nmethod*)cb);
 712         }
 713 #endif //ASSERT
 714       }
 715     }
 716   }
 717 }
 718 
 719 void CodeCache::verify_clean_inline_caches() {
 720 #ifdef ASSERT
 721   NMethodIterator iter(NMethodIterator::only_alive_and_not_unloading);
 722   while(iter.next()) {
 723     nmethod* nm = iter.method();
 724     assert(!nm->is_unloaded(), "Tautology");
 725     nm->verify_clean_inline_caches();
 726     nm->verify();
 727   }
 728 #endif
 729 }
 730 
 731 void CodeCache::verify_icholder_relocations() {
 732 #ifdef ASSERT
 733   // make sure that we aren't leaking icholders
 734   int count = 0;
 735   FOR_ALL_HEAPS(heap) {
 736     FOR_ALL_BLOBS(cb, *heap) {
 737       CompiledMethod *nm = cb->as_compiled_method_or_null();
 738       if (nm != NULL) {
 739         count += nm->verify_icholder_relocations();
 740       }
 741     }
 742   }
 743   assert(count + InlineCacheBuffer::pending_icholder_count() + CompiledICHolder::live_not_claimed_count() ==
 744          CompiledICHolder::live_count(), "must agree");
 745 #endif
 746 }
 747 
 748 // Defer freeing of concurrently cleaned ExceptionCache entries until
 749 // after a global handshake operation.
 750 void CodeCache::release_exception_cache(ExceptionCache* entry) {
 751   if (SafepointSynchronize::is_at_safepoint()) {
 752     delete entry;
 753   } else {
 754     for (;;) {
 755       ExceptionCache* purge_list_head = Atomic::load(&_exception_cache_purge_list);
 756       entry->set_purge_list_next(purge_list_head);
 757       if (Atomic::cmpxchg(&_exception_cache_purge_list, purge_list_head, entry) == purge_list_head) {
 758         break;
 759       }
 760     }
 761   }
 762 }
 763 
 764 // Delete exception caches that have been concurrently unlinked,
 765 // followed by a global handshake operation.
 766 void CodeCache::purge_exception_caches() {
 767   ExceptionCache* curr = _exception_cache_purge_list;
 768   while (curr != NULL) {
 769     ExceptionCache* next = curr->purge_list_next();
 770     delete curr;
 771     curr = next;
 772   }
 773   _exception_cache_purge_list = NULL;
 774 }
 775 
 776 uint8_t CodeCache::_unloading_cycle = 1;
 777 
 778 void CodeCache::increment_unloading_cycle() {
 779   // 2-bit value (see IsUnloadingState in nmethod.cpp for details)
 780   // 0 is reserved for new methods.
 781   _unloading_cycle = (_unloading_cycle + 1) % 4;
 782   if (_unloading_cycle == 0) {
 783     _unloading_cycle = 1;
 784   }
 785 }
 786 
 787 CodeCache::UnloadingScope::UnloadingScope(BoolObjectClosure* is_alive)
 788   : _is_unloading_behaviour(is_alive)
 789 {
 790   _saved_behaviour = IsUnloadingBehaviour::current();
 791   IsUnloadingBehaviour::set_current(&_is_unloading_behaviour);
 792   increment_unloading_cycle();
 793   DependencyContext::cleaning_start();
 794 }
 795 
 796 CodeCache::UnloadingScope::~UnloadingScope() {
 797   IsUnloadingBehaviour::set_current(_saved_behaviour);
 798   DependencyContext::cleaning_end();
 799 }
 800 
 801 void CodeCache::verify_oops() {
 802   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 803   VerifyOopClosure voc;
 804   NMethodIterator iter(NMethodIterator::only_alive_and_not_unloading);
 805   while(iter.next()) {
 806     nmethod* nm = iter.method();
 807     nm->oops_do(&voc);
 808     nm->verify_oop_relocations();
 809   }
 810 }
 811 
 812 int CodeCache::blob_count(int code_blob_type) {
 813   CodeHeap* heap = get_code_heap(code_blob_type);
 814   return (heap != NULL) ? heap->blob_count() : 0;
 815 }
 816 
 817 int CodeCache::blob_count() {
 818   int count = 0;
 819   FOR_ALL_HEAPS(heap) {
 820     count += (*heap)->blob_count();
 821   }
 822   return count;
 823 }
 824 
 825 int CodeCache::nmethod_count(int code_blob_type) {
 826   CodeHeap* heap = get_code_heap(code_blob_type);
 827   return (heap != NULL) ? heap->nmethod_count() : 0;
 828 }
 829 
 830 int CodeCache::nmethod_count() {
 831   int count = 0;
 832   FOR_ALL_NMETHOD_HEAPS(heap) {
 833     count += (*heap)->nmethod_count();
 834   }
 835   return count;
 836 }
 837 
 838 int CodeCache::adapter_count(int code_blob_type) {
 839   CodeHeap* heap = get_code_heap(code_blob_type);
 840   return (heap != NULL) ? heap->adapter_count() : 0;
 841 }
 842 
 843 int CodeCache::adapter_count() {
 844   int count = 0;
 845   FOR_ALL_HEAPS(heap) {
 846     count += (*heap)->adapter_count();
 847   }
 848   return count;
 849 }
 850 
 851 address CodeCache::low_bound(int code_blob_type) {
 852   CodeHeap* heap = get_code_heap(code_blob_type);
 853   return (heap != NULL) ? (address)heap->low_boundary() : NULL;
 854 }
 855 
 856 address CodeCache::high_bound(int code_blob_type) {
 857   CodeHeap* heap = get_code_heap(code_blob_type);
 858   return (heap != NULL) ? (address)heap->high_boundary() : NULL;
 859 }
 860 
 861 size_t CodeCache::capacity() {
 862   size_t cap = 0;
 863   FOR_ALL_ALLOCABLE_HEAPS(heap) {
 864     cap += (*heap)->capacity();
 865   }
 866   return cap;
 867 }
 868 
 869 size_t CodeCache::unallocated_capacity(int code_blob_type) {
 870   CodeHeap* heap = get_code_heap(code_blob_type);
 871   return (heap != NULL) ? heap->unallocated_capacity() : 0;
 872 }
 873 
 874 size_t CodeCache::unallocated_capacity() {
 875   size_t unallocated_cap = 0;
 876   FOR_ALL_ALLOCABLE_HEAPS(heap) {
 877     unallocated_cap += (*heap)->unallocated_capacity();
 878   }
 879   return unallocated_cap;
 880 }
 881 
 882 size_t CodeCache::max_capacity() {
 883   size_t max_cap = 0;
 884   FOR_ALL_ALLOCABLE_HEAPS(heap) {
 885     max_cap += (*heap)->max_capacity();
 886   }
 887   return max_cap;
 888 }
 889 
 890 /**
 891  * Returns the reverse free ratio. E.g., if 25% (1/4) of the code heap
 892  * is free, reverse_free_ratio() returns 4.
 893  */
 894 double CodeCache::reverse_free_ratio(int code_blob_type) {
 895   CodeHeap* heap = get_code_heap(code_blob_type);
 896   if (heap == NULL) {
 897     return 0;
 898   }
 899 
 900   double unallocated_capacity = MAX2((double)heap->unallocated_capacity(), 1.0); // Avoid division by 0;
 901   double max_capacity = (double)heap->max_capacity();
 902   double result = max_capacity / unallocated_capacity;
 903   assert (max_capacity >= unallocated_capacity, "Must be");
 904   assert (result >= 1.0, "reverse_free_ratio must be at least 1. It is %f", result);
 905   return result;
 906 }
 907 
 908 size_t CodeCache::bytes_allocated_in_freelists() {
 909   size_t allocated_bytes = 0;
 910   FOR_ALL_ALLOCABLE_HEAPS(heap) {
 911     allocated_bytes += (*heap)->allocated_in_freelist();
 912   }
 913   return allocated_bytes;
 914 }
 915 
 916 int CodeCache::allocated_segments() {
 917   int number_of_segments = 0;
 918   FOR_ALL_ALLOCABLE_HEAPS(heap) {
 919     number_of_segments += (*heap)->allocated_segments();
 920   }
 921   return number_of_segments;
 922 }
 923 
 924 size_t CodeCache::freelists_length() {
 925   size_t length = 0;
 926   FOR_ALL_ALLOCABLE_HEAPS(heap) {
 927     length += (*heap)->freelist_length();
 928   }
 929   return length;
 930 }
 931 
 932 void icache_init();
 933 
 934 void CodeCache::initialize() {
 935   assert(CodeCacheSegmentSize >= (uintx)CodeEntryAlignment, "CodeCacheSegmentSize must be large enough to align entry points");
 936 #ifdef COMPILER2
 937   assert(CodeCacheSegmentSize >= (uintx)OptoLoopAlignment,  "CodeCacheSegmentSize must be large enough to align inner loops");
 938 #endif
 939   assert(CodeCacheSegmentSize >= sizeof(jdouble),    "CodeCacheSegmentSize must be large enough to align constants");
 940   // This was originally just a check of the alignment, causing failure, instead, round
 941   // the code cache to the page size.  In particular, Solaris is moving to a larger
 942   // default page size.
 943   CodeCacheExpansionSize = align_up(CodeCacheExpansionSize, os::vm_page_size());
 944 
 945   if (SegmentedCodeCache) {
 946     // Use multiple code heaps
 947     initialize_heaps();
 948   } else {
 949     // Use a single code heap
 950     FLAG_SET_ERGO(NonNMethodCodeHeapSize, 0);
 951     FLAG_SET_ERGO(ProfiledCodeHeapSize, 0);
 952     FLAG_SET_ERGO(NonProfiledCodeHeapSize, 0);
 953     ReservedCodeSpace rs = reserve_heap_memory(ReservedCodeCacheSize);
 954     add_heap(rs, "CodeCache", CodeBlobType::All);
 955   }
 956 
 957   // Initialize ICache flush mechanism
 958   // This service is needed for os::register_code_area
 959   icache_init();
 960 
 961   // Give OS a chance to register generated code area.
 962   // This is used on Windows 64 bit platforms to register
 963   // Structured Exception Handlers for our generated code.
 964   os::register_code_area((char*)low_bound(), (char*)high_bound());
 965 }
 966 
 967 void codeCache_init() {
 968   CodeCache::initialize();
 969 }
 970 
 971 //------------------------------------------------------------------------------------------------
 972 
 973 int CodeCache::number_of_nmethods_with_dependencies() {
 974   return _number_of_nmethods_with_dependencies;
 975 }
 976 
 977 void CodeCache::clear_inline_caches() {
 978   assert_locked_or_safepoint(CodeCache_lock);
 979   CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);
 980   while(iter.next()) {
 981     iter.method()->clear_inline_caches();
 982   }
 983 }
 984 
 985 void CodeCache::cleanup_inline_caches() {
 986   assert_locked_or_safepoint(CodeCache_lock);
 987   NMethodIterator iter(NMethodIterator::only_alive_and_not_unloading);
 988   while(iter.next()) {
 989     iter.method()->cleanup_inline_caches(/*clean_all=*/true);
 990   }
 991 }
 992 
 993 // Keeps track of time spent for checking dependencies
 994 NOT_PRODUCT(static elapsedTimer dependentCheckTime;)
 995 
 996 int CodeCache::mark_for_deoptimization(KlassDepChange& changes) {
 997   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 998   int number_of_marked_CodeBlobs = 0;
 999 
1000   // search the hierarchy looking for nmethods which are affected by the loading of this class
1001 
1002   // then search the interfaces this class implements looking for nmethods
1003   // which might be dependent of the fact that an interface only had one
1004   // implementor.
1005   // nmethod::check_all_dependencies works only correctly, if no safepoint
1006   // can happen
1007   NoSafepointVerifier nsv;
1008   for (DepChange::ContextStream str(changes, nsv); str.next(); ) {
1009     Klass* d = str.klass();
1010     number_of_marked_CodeBlobs += InstanceKlass::cast(d)->mark_dependent_nmethods(changes);
1011   }
1012 
1013 #ifndef PRODUCT
1014   if (VerifyDependencies) {
1015     // Object pointers are used as unique identifiers for dependency arguments. This
1016     // is only possible if no safepoint, i.e., GC occurs during the verification code.
1017     dependentCheckTime.start();
1018     nmethod::check_all_dependencies(changes);
1019     dependentCheckTime.stop();
1020   }
1021 #endif
1022 
1023   return number_of_marked_CodeBlobs;
1024 }
1025 
1026 CompiledMethod* CodeCache::find_compiled(void* start) {
1027   CodeBlob *cb = find_blob(start);
1028   assert(cb == NULL || cb->is_compiled(), "did not find an compiled_method");
1029   return (CompiledMethod*)cb;
1030 }
1031 
1032 #if INCLUDE_JVMTI
1033 // RedefineClasses support for unloading nmethods that are dependent on "old" methods.
1034 // We don't really expect this table to grow very large.  If it does, it can become a hashtable.
1035 static GrowableArray<CompiledMethod*>* old_compiled_method_table = NULL;
1036 
1037 static void add_to_old_table(CompiledMethod* c) {
1038   if (old_compiled_method_table == NULL) {
1039     old_compiled_method_table = new (ResourceObj::C_HEAP, mtCode) GrowableArray<CompiledMethod*>(100, mtCode);
1040   }
1041   old_compiled_method_table->push(c);
1042 }
1043 
1044 static void reset_old_method_table() {
1045   if (old_compiled_method_table != NULL) {
1046     delete old_compiled_method_table;
1047     old_compiled_method_table = NULL;
1048   }
1049 }
1050 
1051 // Remove this method when zombied or unloaded.
1052 void CodeCache::unregister_old_nmethod(CompiledMethod* c) {
1053   assert_lock_strong(CodeCache_lock);
1054   if (old_compiled_method_table != NULL) {
1055     int index = old_compiled_method_table->find(c);
1056     if (index != -1) {
1057       old_compiled_method_table->delete_at(index);
1058     }
1059   }
1060 }
1061 
1062 void CodeCache::old_nmethods_do(MetadataClosure* f) {
1063   // Walk old method table and mark those on stack.
1064   int length = 0;
1065   if (old_compiled_method_table != NULL) {
1066     length = old_compiled_method_table->length();
1067     for (int i = 0; i < length; i++) {
1068       CompiledMethod* cm = old_compiled_method_table->at(i);
1069       // Only walk alive nmethods, the dead ones will get removed by the sweeper or GC.
1070       if (cm->is_alive() && !cm->is_unloading()) {
1071         old_compiled_method_table->at(i)->metadata_do(f);
1072       }
1073     }
1074   }
1075   log_debug(redefine, class, nmethod)("Walked %d nmethods for mark_on_stack", length);
1076 }
1077 
1078 // Walk compiled methods and mark dependent methods for deoptimization.
1079 int CodeCache::mark_dependents_for_evol_deoptimization() {
1080   assert(SafepointSynchronize::is_at_safepoint(), "Can only do this at a safepoint!");
1081   // Each redefinition creates a new set of nmethods that have references to "old" Methods
1082   // So delete old method table and create a new one.
1083   reset_old_method_table();
1084 
1085   int number_of_marked_CodeBlobs = 0;
1086   CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);
1087   while(iter.next()) {
1088     CompiledMethod* nm = iter.method();
1089     // Walk all alive nmethods to check for old Methods.
1090     // This includes methods whose inline caches point to old methods, so
1091     // inline cache clearing is unnecessary.
1092     if (nm->has_evol_metadata()) {
1093       nm->mark_for_deoptimization();
1094       add_to_old_table(nm);
1095       number_of_marked_CodeBlobs++;
1096     }
1097   }
1098 
1099   // return total count of nmethods marked for deoptimization, if zero the caller
1100   // can skip deoptimization
1101   return number_of_marked_CodeBlobs;
1102 }
1103 
1104 void CodeCache::mark_all_nmethods_for_evol_deoptimization() {
1105   assert(SafepointSynchronize::is_at_safepoint(), "Can only do this at a safepoint!");
1106   CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);
1107   while(iter.next()) {
1108     CompiledMethod* nm = iter.method();
1109     if (!nm->method()->is_method_handle_intrinsic()) {
1110       nm->mark_for_deoptimization();
1111       if (nm->has_evol_metadata()) {
1112         add_to_old_table(nm);
1113       }
1114     }
1115   }
1116 }
1117 
1118 // Flushes compiled methods dependent on redefined classes, that have already been
1119 // marked for deoptimization.
1120 void CodeCache::flush_evol_dependents() {
1121   assert(SafepointSynchronize::is_at_safepoint(), "Can only do this at a safepoint!");
1122 
1123   // CodeCache can only be updated by a thread_in_VM and they will all be
1124   // stopped during the safepoint so CodeCache will be safe to update without
1125   // holding the CodeCache_lock.
1126 
1127   // At least one nmethod has been marked for deoptimization
1128 
1129   Deoptimization::deoptimize_all_marked();
1130 }
1131 #endif // INCLUDE_JVMTI
1132 
1133 // Mark methods for deopt (if safe or possible).
1134 void CodeCache::mark_all_nmethods_for_deoptimization() {
1135   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1136   CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);
1137   while(iter.next()) {
1138     CompiledMethod* nm = iter.method();
1139     if (!nm->is_native_method()) {
1140       nm->mark_for_deoptimization();
1141     }
1142   }
1143 }
1144 
1145 int CodeCache::mark_for_deoptimization(Method* dependee) {
1146   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1147   int number_of_marked_CodeBlobs = 0;
1148 
1149   CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);
1150   while(iter.next()) {
1151     CompiledMethod* nm = iter.method();
1152     if (nm->is_dependent_on_method(dependee)) {
1153       ResourceMark rm;
1154       nm->mark_for_deoptimization();
1155       number_of_marked_CodeBlobs++;
1156     }
1157   }
1158 
1159   return number_of_marked_CodeBlobs;
1160 }
1161 
1162 void CodeCache::make_marked_nmethods_not_entrant() {
1163   assert_locked_or_safepoint(CodeCache_lock);
1164   CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);
1165   while(iter.next()) {
1166     CompiledMethod* nm = iter.method();
1167     if (nm->is_marked_for_deoptimization()) {
1168       nm->make_not_entrant();
1169     }
1170   }
1171 }
1172 
1173 // Flushes compiled methods dependent on dependee.
1174 void CodeCache::flush_dependents_on(InstanceKlass* dependee) {
1175   assert_lock_strong(Compile_lock);
1176 
1177   if (number_of_nmethods_with_dependencies() == 0) return;
1178 
1179   int marked = 0;
1180   if (dependee->is_linked()) {
1181     // Class initialization state change.
1182     KlassInitDepChange changes(dependee);
1183     marked = mark_for_deoptimization(changes);
1184   } else {
1185     // New class is loaded.
1186     NewKlassDepChange changes(dependee);
1187     marked = mark_for_deoptimization(changes);
1188   }
1189 
1190   if (marked > 0) {
1191     // At least one nmethod has been marked for deoptimization
1192     Deoptimization::deoptimize_all_marked();
1193   }
1194 }
1195 
1196 // Flushes compiled methods dependent on dependee
1197 void CodeCache::flush_dependents_on_method(const methodHandle& m_h) {
1198   // --- Compile_lock is not held. However we are at a safepoint.
1199   assert_locked_or_safepoint(Compile_lock);
1200 
1201   // Compute the dependent nmethods
1202   if (mark_for_deoptimization(m_h()) > 0) {
1203     Deoptimization::deoptimize_all_marked();
1204   }
1205 }
1206 
1207 void CodeCache::verify() {
1208   assert_locked_or_safepoint(CodeCache_lock);
1209   FOR_ALL_HEAPS(heap) {
1210     (*heap)->verify();
1211     FOR_ALL_BLOBS(cb, *heap) {
1212       if (cb->is_alive()) {
1213         cb->verify();
1214       }
1215     }
1216   }
1217 }
1218 
1219 // A CodeHeap is full. Print out warning and report event.
1220 PRAGMA_DIAG_PUSH
1221 PRAGMA_FORMAT_NONLITERAL_IGNORED
1222 void CodeCache::report_codemem_full(int code_blob_type, bool print) {
1223   // Get nmethod heap for the given CodeBlobType and build CodeCacheFull event
1224   CodeHeap* heap = get_code_heap(code_blob_type);
1225   assert(heap != NULL, "heap is null");
1226 
1227   heap->report_full();
1228 
1229   if ((heap->full_count() == 1) || print) {
1230     // Not yet reported for this heap, report
1231     if (SegmentedCodeCache) {
1232       ResourceMark rm;
1233       stringStream msg1_stream, msg2_stream;
1234       msg1_stream.print("%s is full. Compiler has been disabled.",
1235                         get_code_heap_name(code_blob_type));
1236       msg2_stream.print("Try increasing the code heap size using -XX:%s=",
1237                  get_code_heap_flag_name(code_blob_type));
1238       const char *msg1 = msg1_stream.as_string();
1239       const char *msg2 = msg2_stream.as_string();
1240 
1241       log_warning(codecache)("%s", msg1);
1242       log_warning(codecache)("%s", msg2);
1243       warning("%s", msg1);
1244       warning("%s", msg2);
1245     } else {
1246       const char *msg1 = "CodeCache is full. Compiler has been disabled.";
1247       const char *msg2 = "Try increasing the code cache size using -XX:ReservedCodeCacheSize=";
1248 
1249       log_warning(codecache)("%s", msg1);
1250       log_warning(codecache)("%s", msg2);
1251       warning("%s", msg1);
1252       warning("%s", msg2);
1253     }
1254     ResourceMark rm;
1255     stringStream s;
1256     // Dump code cache into a buffer before locking the tty.
1257     {
1258       MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1259       print_summary(&s);
1260     }
1261     {
1262       ttyLocker ttyl;
1263       tty->print("%s", s.as_string());
1264     }
1265 
1266     if (heap->full_count() == 1) {
1267       if (PrintCodeHeapAnalytics) {
1268         CompileBroker::print_heapinfo(tty, "all", 4096); // details, may be a lot!
1269       }
1270     }
1271   }
1272 
1273   EventCodeCacheFull event;
1274   if (event.should_commit()) {
1275     event.set_codeBlobType((u1)code_blob_type);
1276     event.set_startAddress((u8)heap->low_boundary());
1277     event.set_commitedTopAddress((u8)heap->high());
1278     event.set_reservedTopAddress((u8)heap->high_boundary());
1279     event.set_entryCount(heap->blob_count());
1280     event.set_methodCount(heap->nmethod_count());
1281     event.set_adaptorCount(heap->adapter_count());
1282     event.set_unallocatedCapacity(heap->unallocated_capacity());
1283     event.set_fullCount(heap->full_count());
1284     event.commit();
1285   }
1286 }
1287 PRAGMA_DIAG_POP
1288 
1289 void CodeCache::print_memory_overhead() {
1290   size_t wasted_bytes = 0;
1291   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1292       CodeHeap* curr_heap = *heap;
1293       for (CodeBlob* cb = (CodeBlob*)curr_heap->first(); cb != NULL; cb = (CodeBlob*)curr_heap->next(cb)) {
1294         HeapBlock* heap_block = ((HeapBlock*)cb) - 1;
1295         wasted_bytes += heap_block->length() * CodeCacheSegmentSize - cb->size();
1296       }
1297   }
1298   // Print bytes that are allocated in the freelist
1299   ttyLocker ttl;
1300   tty->print_cr("Number of elements in freelist: " SSIZE_FORMAT,       freelists_length());
1301   tty->print_cr("Allocated in freelist:          " SSIZE_FORMAT "kB",  bytes_allocated_in_freelists()/K);
1302   tty->print_cr("Unused bytes in CodeBlobs:      " SSIZE_FORMAT "kB",  (wasted_bytes/K));
1303   tty->print_cr("Segment map size:               " SSIZE_FORMAT "kB",  allocated_segments()/K); // 1 byte per segment
1304 }
1305 
1306 //------------------------------------------------------------------------------------------------
1307 // Non-product version
1308 
1309 #ifndef PRODUCT
1310 
1311 void CodeCache::print_trace(const char* event, CodeBlob* cb, int size) {
1312   if (PrintCodeCache2) {  // Need to add a new flag
1313     ResourceMark rm;
1314     if (size == 0)  size = cb->size();
1315     tty->print_cr("CodeCache %s:  addr: " INTPTR_FORMAT ", size: 0x%x", event, p2i(cb), size);
1316   }
1317 }
1318 
1319 void CodeCache::print_internals() {
1320   int nmethodCount = 0;
1321   int runtimeStubCount = 0;
1322   int adapterCount = 0;
1323   int deoptimizationStubCount = 0;
1324   int uncommonTrapStubCount = 0;
1325   int bufferBlobCount = 0;
1326   int total = 0;
1327   int nmethodAlive = 0;
1328   int nmethodNotEntrant = 0;
1329   int nmethodZombie = 0;
1330   int nmethodUnloaded = 0;
1331   int nmethodJava = 0;
1332   int nmethodNative = 0;
1333   int max_nm_size = 0;
1334   ResourceMark rm;
1335 
1336   int i = 0;
1337   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1338     if ((_nmethod_heaps->length() >= 1) && Verbose) {
1339       tty->print_cr("-- %s --", (*heap)->name());
1340     }
1341     FOR_ALL_BLOBS(cb, *heap) {
1342       total++;
1343       if (cb->is_nmethod()) {
1344         nmethod* nm = (nmethod*)cb;
1345 
1346         if (Verbose && nm->method() != NULL) {
1347           ResourceMark rm;
1348           char *method_name = nm->method()->name_and_sig_as_C_string();
1349           tty->print("%s", method_name);
1350           if(nm->is_alive()) { tty->print_cr(" alive"); }
1351           if(nm->is_not_entrant()) { tty->print_cr(" not-entrant"); }
1352           if(nm->is_zombie()) { tty->print_cr(" zombie"); }
1353         }
1354 
1355         nmethodCount++;
1356 
1357         if(nm->is_alive()) { nmethodAlive++; }
1358         if(nm->is_not_entrant()) { nmethodNotEntrant++; }
1359         if(nm->is_zombie()) { nmethodZombie++; }
1360         if(nm->is_unloaded()) { nmethodUnloaded++; }
1361         if(nm->method() != NULL && nm->is_native_method()) { nmethodNative++; }
1362 
1363         if(nm->method() != NULL && nm->is_java_method()) {
1364           nmethodJava++;
1365           max_nm_size = MAX2(max_nm_size, nm->size());
1366         }
1367       } else if (cb->is_runtime_stub()) {
1368         runtimeStubCount++;
1369       } else if (cb->is_deoptimization_stub()) {
1370         deoptimizationStubCount++;
1371       } else if (cb->is_uncommon_trap_stub()) {
1372         uncommonTrapStubCount++;
1373       } else if (cb->is_adapter_blob()) {
1374         adapterCount++;
1375       } else if (cb->is_buffer_blob()) {
1376         bufferBlobCount++;
1377       }
1378     }
1379   }
1380 
1381   int bucketSize = 512;
1382   int bucketLimit = max_nm_size / bucketSize + 1;
1383   int *buckets = NEW_C_HEAP_ARRAY(int, bucketLimit, mtCode);
1384   memset(buckets, 0, sizeof(int) * bucketLimit);
1385 
1386   NMethodIterator iter(NMethodIterator::all_blobs);
1387   while(iter.next()) {
1388     nmethod* nm = iter.method();
1389     if(nm->method() != NULL && nm->is_java_method()) {
1390       buckets[nm->size() / bucketSize]++;
1391     }
1392   }
1393 
1394   tty->print_cr("Code Cache Entries (total of %d)",total);
1395   tty->print_cr("-------------------------------------------------");
1396   tty->print_cr("nmethods: %d",nmethodCount);
1397   tty->print_cr("\talive: %d",nmethodAlive);
1398   tty->print_cr("\tnot_entrant: %d",nmethodNotEntrant);
1399   tty->print_cr("\tzombie: %d",nmethodZombie);
1400   tty->print_cr("\tunloaded: %d",nmethodUnloaded);
1401   tty->print_cr("\tjava: %d",nmethodJava);
1402   tty->print_cr("\tnative: %d",nmethodNative);
1403   tty->print_cr("runtime_stubs: %d",runtimeStubCount);
1404   tty->print_cr("adapters: %d",adapterCount);
1405   tty->print_cr("buffer blobs: %d",bufferBlobCount);
1406   tty->print_cr("deoptimization_stubs: %d",deoptimizationStubCount);
1407   tty->print_cr("uncommon_traps: %d",uncommonTrapStubCount);
1408   tty->print_cr("\nnmethod size distribution (non-zombie java)");
1409   tty->print_cr("-------------------------------------------------");
1410 
1411   for(int i=0; i<bucketLimit; i++) {
1412     if(buckets[i] != 0) {
1413       tty->print("%d - %d bytes",i*bucketSize,(i+1)*bucketSize);
1414       tty->fill_to(40);
1415       tty->print_cr("%d",buckets[i]);
1416     }
1417   }
1418 
1419   FREE_C_HEAP_ARRAY(int, buckets);
1420   print_memory_overhead();
1421 }
1422 
1423 #endif // !PRODUCT
1424 
1425 void CodeCache::print() {
1426   print_summary(tty);
1427 
1428 #ifndef PRODUCT
1429   if (!Verbose) return;
1430 
1431   CodeBlob_sizes live;
1432   CodeBlob_sizes dead;
1433 
1434   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1435     FOR_ALL_BLOBS(cb, *heap) {
1436       if (!cb->is_alive()) {
1437         dead.add(cb);
1438       } else {
1439         live.add(cb);
1440       }
1441     }
1442   }
1443 
1444   tty->print_cr("CodeCache:");
1445   tty->print_cr("nmethod dependency checking time %fs", dependentCheckTime.seconds());
1446 
1447   if (!live.is_empty()) {
1448     live.print("live");
1449   }
1450   if (!dead.is_empty()) {
1451     dead.print("dead");
1452   }
1453 
1454   if (WizardMode) {
1455      // print the oop_map usage
1456     int code_size = 0;
1457     int number_of_blobs = 0;
1458     int number_of_oop_maps = 0;
1459     int map_size = 0;
1460     FOR_ALL_ALLOCABLE_HEAPS(heap) {
1461       FOR_ALL_BLOBS(cb, *heap) {
1462         if (cb->is_alive()) {
1463           number_of_blobs++;
1464           code_size += cb->code_size();
1465           ImmutableOopMapSet* set = cb->oop_maps();
1466           if (set != NULL) {
1467             number_of_oop_maps += set->count();
1468             map_size           += set->nr_of_bytes();
1469           }
1470         }
1471       }
1472     }
1473     tty->print_cr("OopMaps");
1474     tty->print_cr("  #blobs    = %d", number_of_blobs);
1475     tty->print_cr("  code size = %d", code_size);
1476     tty->print_cr("  #oop_maps = %d", number_of_oop_maps);
1477     tty->print_cr("  map size  = %d", map_size);
1478   }
1479 
1480 #endif // !PRODUCT
1481 }
1482 
1483 void CodeCache::print_summary(outputStream* st, bool detailed) {
1484   int full_count = 0;
1485   FOR_ALL_HEAPS(heap_iterator) {
1486     CodeHeap* heap = (*heap_iterator);
1487     size_t total = (heap->high_boundary() - heap->low_boundary());
1488     if (_heaps->length() >= 1) {
1489       st->print("%s:", heap->name());
1490     } else {
1491       st->print("CodeCache:");
1492     }
1493     st->print_cr(" size=" SIZE_FORMAT "Kb used=" SIZE_FORMAT
1494                  "Kb max_used=" SIZE_FORMAT "Kb free=" SIZE_FORMAT "Kb",
1495                  total/K, (total - heap->unallocated_capacity())/K,
1496                  heap->max_allocated_capacity()/K, heap->unallocated_capacity()/K);
1497 
1498     if (detailed) {
1499       st->print_cr(" bounds [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT "]",
1500                    p2i(heap->low_boundary()),
1501                    p2i(heap->high()),
1502                    p2i(heap->high_boundary()));
1503 
1504       full_count += get_codemem_full_count(heap->code_blob_type());
1505     }
1506   }
1507 
1508   if (detailed) {
1509     st->print_cr(" total_blobs=" UINT32_FORMAT " nmethods=" UINT32_FORMAT
1510                        " adapters=" UINT32_FORMAT,
1511                        blob_count(), nmethod_count(), adapter_count());
1512     st->print_cr(" compilation: %s", CompileBroker::should_compile_new_jobs() ?
1513                  "enabled" : Arguments::mode() == Arguments::_int ?
1514                  "disabled (interpreter mode)" :
1515                  "disabled (not enough contiguous free space left)");
1516     st->print_cr("              stopped_count=%d, restarted_count=%d",
1517                  CompileBroker::get_total_compiler_stopped_count(),
1518                  CompileBroker::get_total_compiler_restarted_count());
1519     st->print_cr(" full_count=%d", full_count);
1520   }
1521 }
1522 
1523 void CodeCache::print_codelist(outputStream* st) {
1524   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1525 
1526   CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);
1527   while (iter.next()) {
1528     CompiledMethod* cm = iter.method();
1529     ResourceMark rm;
1530     char* method_name = cm->method()->name_and_sig_as_C_string();
1531     st->print_cr("%d %d %d %s [" INTPTR_FORMAT ", " INTPTR_FORMAT " - " INTPTR_FORMAT "]",
1532                  cm->compile_id(), cm->comp_level(), cm->get_state(),
1533                  method_name,
1534                  (intptr_t)cm->header_begin(), (intptr_t)cm->code_begin(), (intptr_t)cm->code_end());
1535   }
1536 }
1537 
1538 void CodeCache::print_layout(outputStream* st) {
1539   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1540   ResourceMark rm;
1541   print_summary(st, true);
1542 }
1543 
1544 void CodeCache::log_state(outputStream* st) {
1545   st->print(" total_blobs='" UINT32_FORMAT "' nmethods='" UINT32_FORMAT "'"
1546             " adapters='" UINT32_FORMAT "' free_code_cache='" SIZE_FORMAT "'",
1547             blob_count(), nmethod_count(), adapter_count(),
1548             unallocated_capacity());
1549 }
1550 
1551 #ifdef LINUX
1552 void CodeCache::write_perf_map() {
1553   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1554 
1555   // Perf expects to find the map file at /tmp/perf-<pid>.map.
1556   char fname[32];
1557   jio_snprintf(fname, sizeof(fname), "/tmp/perf-%d.map", os::current_process_id());
1558 
1559   fileStream fs(fname, "w");
1560   if (!fs.is_open()) {
1561     log_warning(codecache)("Failed to create %s for perf map", fname);
1562     return;
1563   }
1564 
1565   AllCodeBlobsIterator iter(AllCodeBlobsIterator::only_alive_and_not_unloading);
1566   while (iter.next()) {
1567     CodeBlob *cb = iter.method();
1568     ResourceMark rm;
1569     const char* method_name =
1570       cb->is_compiled() ? cb->as_compiled_method()->method()->external_name()
1571                         : cb->name();
1572     fs.print_cr(INTPTR_FORMAT " " INTPTR_FORMAT " %s",
1573                 (intptr_t)cb->code_begin(), (intptr_t)cb->code_size(),
1574                 method_name);
1575   }
1576 }
1577 #endif // LINUX
1578 
1579 //---<  BEGIN  >--- CodeHeap State Analytics.
1580 
1581 void CodeCache::aggregate(outputStream *out, size_t granularity) {
1582   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1583     CodeHeapState::aggregate(out, (*heap), granularity);
1584   }
1585 }
1586 
1587 void CodeCache::discard(outputStream *out) {
1588   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1589     CodeHeapState::discard(out, (*heap));
1590   }
1591 }
1592 
1593 void CodeCache::print_usedSpace(outputStream *out) {
1594   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1595     CodeHeapState::print_usedSpace(out, (*heap));
1596   }
1597 }
1598 
1599 void CodeCache::print_freeSpace(outputStream *out) {
1600   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1601     CodeHeapState::print_freeSpace(out, (*heap));
1602   }
1603 }
1604 
1605 void CodeCache::print_count(outputStream *out) {
1606   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1607     CodeHeapState::print_count(out, (*heap));
1608   }
1609 }
1610 
1611 void CodeCache::print_space(outputStream *out) {
1612   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1613     CodeHeapState::print_space(out, (*heap));
1614   }
1615 }
1616 
1617 void CodeCache::print_age(outputStream *out) {
1618   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1619     CodeHeapState::print_age(out, (*heap));
1620   }
1621 }
1622 
1623 void CodeCache::print_names(outputStream *out) {
1624   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1625     CodeHeapState::print_names(out, (*heap));
1626   }
1627 }
1628 //---<  END  >--- CodeHeap State Analytics.