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