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