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