1 /*
   2  * Copyright (c) 1997, 2016, 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(cb)) {
 421       guarantee((char*) cb >= (*heap)->low_boundary(),
 422                 "Code blob " INTPTR_FORMAT " should be after heap low boundary " INTPTR_FORMAT,
 423                 p2i(cb), p2i((*heap)->low_boundary()));
 424       return *heap;
 425     }
 426   }
 427   ShouldNotReachHere();
 428   return NULL;
 429 }
 430 
 431 CodeHeap* CodeCache::get_code_heap(int code_blob_type) {
 432   FOR_ALL_HEAPS(heap) {
 433     if ((*heap)->accepts(code_blob_type)) {
 434       return *heap;
 435     }
 436   }
 437   return NULL;
 438 }
 439 
 440 CodeBlob* CodeCache::first_blob(CodeHeap* heap) {
 441   assert_locked_or_safepoint(CodeCache_lock);
 442   assert(heap != NULL, "heap is null");
 443   return (CodeBlob*)heap->first();
 444 }
 445 
 446 CodeBlob* CodeCache::first_blob(int code_blob_type) {
 447   if (heap_available(code_blob_type)) {
 448     return first_blob(get_code_heap(code_blob_type));
 449   } else {
 450     return NULL;
 451   }
 452 }
 453 
 454 CodeBlob* CodeCache::next_blob(CodeHeap* heap, CodeBlob* cb) {
 455   assert_locked_or_safepoint(CodeCache_lock);
 456   assert(heap != NULL, "heap is null");
 457   return (CodeBlob*)heap->next(cb);
 458 }
 459 
 460 /**
 461  * Do not seize the CodeCache lock here--if the caller has not
 462  * already done so, we are going to lose bigtime, since the code
 463  * cache will contain a garbage CodeBlob until the caller can
 464  * run the constructor for the CodeBlob subclass he is busy
 465  * instantiating.
 466  */
 467 CodeBlob* CodeCache::allocate(int size, int code_blob_type, int orig_code_blob_type) {
 468   // Possibly wakes up the sweeper thread.
 469   NMethodSweeper::notify(code_blob_type);
 470   assert_locked_or_safepoint(CodeCache_lock);
 471   assert(size > 0, "Code cache allocation request must be > 0 but is %d", size);
 472   if (size <= 0) {
 473     return NULL;
 474   }
 475   CodeBlob* cb = NULL;
 476 
 477   // Get CodeHeap for the given CodeBlobType
 478   CodeHeap* heap = get_code_heap(code_blob_type);
 479   assert(heap != NULL, "heap is null");
 480 
 481   while (true) {
 482     cb = (CodeBlob*)heap->allocate(size);
 483     if (cb != NULL) break;
 484     if (!heap->expand_by(CodeCacheExpansionSize)) {
 485       // Save original type for error reporting
 486       if (orig_code_blob_type == CodeBlobType::All) {
 487         orig_code_blob_type = code_blob_type;
 488       }
 489       // Expansion failed
 490       if (SegmentedCodeCache) {
 491         // Fallback solution: Try to store code in another code heap.
 492         // NonNMethod -> MethodNonProfiled -> MethodProfiled (-> MethodNonProfiled)
 493         // Note that in the sweeper, we check the reverse_free_ratio of the code heap
 494         // and force stack scanning if less than 10% of the code heap are free.
 495         int type = code_blob_type;
 496         switch (type) {
 497         case CodeBlobType::NonNMethod:
 498           type = CodeBlobType::MethodNonProfiled;
 499           break;
 500         case CodeBlobType::MethodNonProfiled:
 501           type = CodeBlobType::MethodProfiled;
 502           break;
 503         case CodeBlobType::MethodProfiled:
 504           // Avoid loop if we already tried that code heap
 505           if (type == orig_code_blob_type) {
 506             type = CodeBlobType::MethodNonProfiled;
 507           }
 508           break;
 509         }
 510         if (type != code_blob_type && type != orig_code_blob_type && heap_available(type)) {
 511           if (PrintCodeCacheExtension) {
 512             tty->print_cr("Extension of %s failed. Trying to allocate in %s.",
 513                           heap->name(), get_code_heap(type)->name());
 514           }
 515           return allocate(size, type, orig_code_blob_type);
 516         }
 517       }
 518       MutexUnlockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 519       CompileBroker::handle_full_code_cache(orig_code_blob_type);
 520       return NULL;
 521     }
 522     if (PrintCodeCacheExtension) {
 523       ResourceMark rm;
 524       if (_nmethod_heaps->length() >= 1) {
 525         tty->print("%s", heap->name());
 526       } else {
 527         tty->print("CodeCache");
 528       }
 529       tty->print_cr(" extended to [" INTPTR_FORMAT ", " INTPTR_FORMAT "] (" SSIZE_FORMAT " bytes)",
 530                     (intptr_t)heap->low_boundary(), (intptr_t)heap->high(),
 531                     (address)heap->high() - (address)heap->low_boundary());
 532     }
 533   }
 534   print_trace("allocation", cb, size);
 535   return cb;
 536 }
 537 
 538 void CodeCache::free(CodeBlob* cb) {
 539   assert_locked_or_safepoint(CodeCache_lock);
 540   CodeHeap* heap = get_code_heap(cb);
 541   print_trace("free", cb);
 542   if (cb->is_nmethod()) {
 543     heap->set_nmethod_count(heap->nmethod_count() - 1);
 544     if (((nmethod *)cb)->has_dependencies()) {
 545       _number_of_nmethods_with_dependencies--;
 546     }
 547   }
 548   if (cb->is_adapter_blob()) {
 549     heap->set_adapter_count(heap->adapter_count() - 1);
 550   }
 551 
 552   // Get heap for given CodeBlob and deallocate
 553   get_code_heap(cb)->deallocate(cb);
 554 
 555   assert(heap->blob_count() >= 0, "sanity check");
 556 }
 557 
 558 void CodeCache::commit(CodeBlob* cb) {
 559   // this is called by nmethod::nmethod, which must already own CodeCache_lock
 560   assert_locked_or_safepoint(CodeCache_lock);
 561   CodeHeap* heap = get_code_heap(cb);
 562   if (cb->is_nmethod()) {
 563     heap->set_nmethod_count(heap->nmethod_count() + 1);
 564     if (((nmethod *)cb)->has_dependencies()) {
 565       _number_of_nmethods_with_dependencies++;
 566     }
 567   }
 568   if (cb->is_adapter_blob()) {
 569     heap->set_adapter_count(heap->adapter_count() + 1);
 570   }
 571 
 572   // flush the hardware I-cache
 573   ICache::invalidate_range(cb->content_begin(), cb->content_size());
 574 }
 575 
 576 bool CodeCache::contains(void *p) {
 577   // S390 uses contains() in current_frame(), which is used before
 578   // code cache initialization if NativeMemoryTracking=detail is set.
 579   S390_ONLY(if (_heaps == NULL) return false;)
 580   // It should be ok to call contains without holding a lock.
 581   FOR_ALL_HEAPS(heap) {
 582     if ((*heap)->contains(p)) {
 583       return true;
 584     }
 585   }
 586   return false;
 587 }
 588 
 589 bool CodeCache::contains(nmethod *nm) {
 590   return contains((void *)nm);
 591 }
 592 
 593 // This method is safe to call without holding the CodeCache_lock, as long as a dead CodeBlob is not
 594 // looked up (i.e., one that has been marked for deletion). It only depends on the _segmap to contain
 595 // valid indices, which it will always do, as long as the CodeBlob is not in the process of being recycled.
 596 CodeBlob* CodeCache::find_blob(void* start) {
 597   CodeBlob* result = find_blob_unsafe(start);
 598   // We could potentially look up non_entrant methods
 599   guarantee(result == NULL || !result->is_zombie() || result->is_locked_by_vm() || is_error_reported(), "unsafe access to zombie method");
 600   return result;
 601 }
 602 
 603 // Lookup that does not fail if you lookup a zombie method (if you call this, be sure to know
 604 // what you are doing)
 605 CodeBlob* CodeCache::find_blob_unsafe(void* start) {
 606   // NMT can walk the stack before code cache is created
 607   if (_heaps != NULL && !_heaps->is_empty()) {
 608     FOR_ALL_HEAPS(heap) {
 609       CodeBlob* result = (*heap)->find_blob_unsafe(start);
 610       if (result != NULL) {
 611         return result;
 612       }
 613     }
 614   }
 615   return NULL;
 616 }
 617 
 618 nmethod* CodeCache::find_nmethod(void* start) {
 619   CodeBlob* cb = find_blob(start);
 620   assert(cb->is_nmethod(), "did not find an nmethod");
 621   return (nmethod*)cb;
 622 }
 623 
 624 void CodeCache::blobs_do(void f(CodeBlob* nm)) {
 625   assert_locked_or_safepoint(CodeCache_lock);
 626   FOR_ALL_NMETHOD_HEAPS(heap) {
 627     FOR_ALL_BLOBS(cb, *heap) {
 628       f(cb);
 629     }
 630   }
 631 }
 632 
 633 void CodeCache::nmethods_do(void f(nmethod* nm)) {
 634   assert_locked_or_safepoint(CodeCache_lock);
 635   NMethodIterator iter;
 636   while(iter.next()) {
 637     f(iter.method());
 638   }
 639 }
 640 
 641 void CodeCache::metadata_do(void f(Metadata* m)) {
 642   assert_locked_or_safepoint(CodeCache_lock);
 643   NMethodIterator iter;
 644   while(iter.next_alive()) {
 645     iter.method()->metadata_do(f);
 646   }
 647   AOTLoader::metadata_do(f);
 648 }
 649 
 650 int CodeCache::alignment_unit() {
 651   return (int)_heaps->first()->alignment_unit();
 652 }
 653 
 654 int CodeCache::alignment_offset() {
 655   return (int)_heaps->first()->alignment_offset();
 656 }
 657 
 658 // Mark nmethods for unloading if they contain otherwise unreachable oops.
 659 void CodeCache::do_unloading(BoolObjectClosure* is_alive, bool unloading_occurred) {
 660   assert_locked_or_safepoint(CodeCache_lock);
 661   CompiledMethodIterator iter;
 662   while(iter.next_alive()) {
 663     iter.method()->do_unloading(is_alive, unloading_occurred);
 664   }
 665 }
 666 
 667 void CodeCache::blobs_do(CodeBlobClosure* f) {
 668   assert_locked_or_safepoint(CodeCache_lock);
 669   FOR_ALL_NMETHOD_HEAPS(heap) {
 670     FOR_ALL_BLOBS(cb, *heap) {
 671       if (cb->is_alive()) {
 672         f->do_code_blob(cb);
 673 #ifdef ASSERT
 674         if (cb->is_nmethod())
 675         ((nmethod*)cb)->verify_scavenge_root_oops();
 676 #endif //ASSERT
 677       }
 678     }
 679   }
 680 }
 681 
 682 // Walk the list of methods which might contain non-perm oops.
 683 void CodeCache::scavenge_root_nmethods_do(CodeBlobToOopClosure* f) {
 684   assert_locked_or_safepoint(CodeCache_lock);
 685 
 686   if (UseG1GC) {
 687     return;
 688   }
 689 
 690   const bool fix_relocations = f->fix_relocations();
 691   debug_only(mark_scavenge_root_nmethods());
 692 
 693   nmethod* prev = NULL;
 694   nmethod* cur = scavenge_root_nmethods();
 695   while (cur != NULL) {
 696     debug_only(cur->clear_scavenge_root_marked());
 697     assert(cur->scavenge_root_not_marked(), "");
 698     assert(cur->on_scavenge_root_list(), "else shouldn't be on this list");
 699 
 700     bool is_live = (!cur->is_zombie() && !cur->is_unloaded());
 701     if (TraceScavenge) {
 702       cur->print_on(tty, is_live ? "scavenge root" : "dead scavenge root"); tty->cr();
 703     }
 704     if (is_live) {
 705       // Perform cur->oops_do(f), maybe just once per nmethod.
 706       f->do_code_blob(cur);
 707     }
 708     nmethod* const next = cur->scavenge_root_link();
 709     // The scavengable nmethod list must contain all methods with scavengable
 710     // oops. It is safe to include more nmethod on the list, but we do not
 711     // expect any live non-scavengable nmethods on the list.
 712     if (fix_relocations) {
 713       if (!is_live || !cur->detect_scavenge_root_oops()) {
 714         unlink_scavenge_root_nmethod(cur, prev);
 715       } else {
 716         prev = cur;
 717       }
 718     }
 719     cur = next;
 720   }
 721 
 722   // Check for stray marks.
 723   debug_only(verify_perm_nmethods(NULL));
 724 }
 725 
 726 void CodeCache::add_scavenge_root_nmethod(nmethod* nm) {
 727   assert_locked_or_safepoint(CodeCache_lock);
 728 
 729   if (UseG1GC) {
 730     return;
 731   }
 732 
 733   nm->set_on_scavenge_root_list();
 734   nm->set_scavenge_root_link(_scavenge_root_nmethods);
 735   set_scavenge_root_nmethods(nm);
 736   print_trace("add_scavenge_root", nm);
 737 }
 738 
 739 void CodeCache::unlink_scavenge_root_nmethod(nmethod* nm, nmethod* prev) {
 740   assert_locked_or_safepoint(CodeCache_lock);
 741 
 742   assert((prev == NULL && scavenge_root_nmethods() == nm) ||
 743          (prev != NULL && prev->scavenge_root_link() == nm), "precondition");
 744 
 745   assert(!UseG1GC, "G1 does not use the scavenge_root_nmethods list");
 746 
 747   print_trace("unlink_scavenge_root", nm);
 748   if (prev == NULL) {
 749     set_scavenge_root_nmethods(nm->scavenge_root_link());
 750   } else {
 751     prev->set_scavenge_root_link(nm->scavenge_root_link());
 752   }
 753   nm->set_scavenge_root_link(NULL);
 754   nm->clear_on_scavenge_root_list();
 755 }
 756 
 757 void CodeCache::drop_scavenge_root_nmethod(nmethod* nm) {
 758   assert_locked_or_safepoint(CodeCache_lock);
 759 
 760   if (UseG1GC) {
 761     return;
 762   }
 763 
 764   print_trace("drop_scavenge_root", nm);
 765   nmethod* prev = NULL;
 766   for (nmethod* cur = scavenge_root_nmethods(); cur != NULL; cur = cur->scavenge_root_link()) {
 767     if (cur == nm) {
 768       unlink_scavenge_root_nmethod(cur, prev);
 769       return;
 770     }
 771     prev = cur;
 772   }
 773   assert(false, "should have been on list");
 774 }
 775 
 776 void CodeCache::prune_scavenge_root_nmethods() {
 777   assert_locked_or_safepoint(CodeCache_lock);
 778 
 779   if (UseG1GC) {
 780     return;
 781   }
 782 
 783   debug_only(mark_scavenge_root_nmethods());
 784 
 785   nmethod* last = NULL;
 786   nmethod* cur = scavenge_root_nmethods();
 787   while (cur != NULL) {
 788     nmethod* next = cur->scavenge_root_link();
 789     debug_only(cur->clear_scavenge_root_marked());
 790     assert(cur->scavenge_root_not_marked(), "");
 791     assert(cur->on_scavenge_root_list(), "else shouldn't be on this list");
 792 
 793     if (!cur->is_zombie() && !cur->is_unloaded()
 794         && cur->detect_scavenge_root_oops()) {
 795       // Keep it.  Advance 'last' to prevent deletion.
 796       last = cur;
 797     } else {
 798       // Prune it from the list, so we don't have to look at it any more.
 799       print_trace("prune_scavenge_root", cur);
 800       unlink_scavenge_root_nmethod(cur, last);
 801     }
 802     cur = next;
 803   }
 804 
 805   // Check for stray marks.
 806   debug_only(verify_perm_nmethods(NULL));
 807 }
 808 
 809 #ifndef PRODUCT
 810 void CodeCache::asserted_non_scavengable_nmethods_do(CodeBlobClosure* f) {
 811   if (UseG1GC) {
 812     return;
 813   }
 814 
 815   // While we are here, verify the integrity of the list.
 816   mark_scavenge_root_nmethods();
 817   for (nmethod* cur = scavenge_root_nmethods(); cur != NULL; cur = cur->scavenge_root_link()) {
 818     assert(cur->on_scavenge_root_list(), "else shouldn't be on this list");
 819     cur->clear_scavenge_root_marked();
 820   }
 821   verify_perm_nmethods(f);
 822 }
 823 
 824 // Temporarily mark nmethods that are claimed to be on the non-perm list.
 825 void CodeCache::mark_scavenge_root_nmethods() {
 826   NMethodIterator iter;
 827   while(iter.next_alive()) {
 828     nmethod* nm = iter.method();
 829     assert(nm->scavenge_root_not_marked(), "clean state");
 830     if (nm->on_scavenge_root_list())
 831       nm->set_scavenge_root_marked();
 832   }
 833 }
 834 
 835 // If the closure is given, run it on the unlisted nmethods.
 836 // Also make sure that the effects of mark_scavenge_root_nmethods is gone.
 837 void CodeCache::verify_perm_nmethods(CodeBlobClosure* f_or_null) {
 838   NMethodIterator iter;
 839   while(iter.next_alive()) {
 840     nmethod* nm = iter.method();
 841     bool call_f = (f_or_null != NULL);
 842     assert(nm->scavenge_root_not_marked(), "must be already processed");
 843     if (nm->on_scavenge_root_list())
 844       call_f = false;  // don't show this one to the client
 845     nm->verify_scavenge_root_oops();
 846     if (call_f)  f_or_null->do_code_blob(nm);
 847   }
 848 }
 849 #endif //PRODUCT
 850 
 851 void CodeCache::verify_clean_inline_caches() {
 852 #ifdef ASSERT
 853   NMethodIterator iter;
 854   while(iter.next_alive()) {
 855     nmethod* nm = iter.method();
 856     assert(!nm->is_unloaded(), "Tautology");
 857     nm->verify_clean_inline_caches();
 858     nm->verify();
 859   }
 860 #endif
 861 }
 862 
 863 void CodeCache::verify_icholder_relocations() {
 864 #ifdef ASSERT
 865   // make sure that we aren't leaking icholders
 866   int count = 0;
 867   FOR_ALL_HEAPS(heap) {
 868     FOR_ALL_BLOBS(cb, *heap) {
 869       CompiledMethod *nm = cb->as_compiled_method_or_null();
 870       if (nm != NULL) {
 871         count += nm->verify_icholder_relocations();
 872       }
 873     }
 874   }
 875   assert(count + InlineCacheBuffer::pending_icholder_count() + CompiledICHolder::live_not_claimed_count() ==
 876          CompiledICHolder::live_count(), "must agree");
 877 #endif
 878 }
 879 
 880 void CodeCache::gc_prologue() {
 881 }
 882 
 883 void CodeCache::gc_epilogue() {
 884   assert_locked_or_safepoint(CodeCache_lock);
 885   NOT_DEBUG(if (needs_cache_clean())) {
 886     CompiledMethodIterator iter;
 887     while(iter.next_alive()) {
 888       CompiledMethod* cm = iter.method();
 889       assert(!cm->is_unloaded(), "Tautology");
 890       DEBUG_ONLY(if (needs_cache_clean())) {
 891         cm->cleanup_inline_caches();
 892       }
 893       DEBUG_ONLY(cm->verify());
 894       DEBUG_ONLY(cm->verify_oop_relocations());
 895     }
 896   }
 897 
 898   set_needs_cache_clean(false);
 899   prune_scavenge_root_nmethods();
 900 
 901   verify_icholder_relocations();
 902 }
 903 
 904 void CodeCache::verify_oops() {
 905   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 906   VerifyOopClosure voc;
 907   NMethodIterator iter;
 908   while(iter.next_alive()) {
 909     nmethod* nm = iter.method();
 910     nm->oops_do(&voc);
 911     nm->verify_oop_relocations();
 912   }
 913 }
 914 
 915 int CodeCache::blob_count(int code_blob_type) {
 916   CodeHeap* heap = get_code_heap(code_blob_type);
 917   return (heap != NULL) ? heap->blob_count() : 0;
 918 }
 919 
 920 int CodeCache::blob_count() {
 921   int count = 0;
 922   FOR_ALL_HEAPS(heap) {
 923     count += (*heap)->blob_count();
 924   }
 925   return count;
 926 }
 927 
 928 int CodeCache::nmethod_count(int code_blob_type) {
 929   CodeHeap* heap = get_code_heap(code_blob_type);
 930   return (heap != NULL) ? heap->nmethod_count() : 0;
 931 }
 932 
 933 int CodeCache::nmethod_count() {
 934   int count = 0;
 935   FOR_ALL_NMETHOD_HEAPS(heap) {
 936     count += (*heap)->nmethod_count();
 937   }
 938   return count;
 939 }
 940 
 941 int CodeCache::adapter_count(int code_blob_type) {
 942   CodeHeap* heap = get_code_heap(code_blob_type);
 943   return (heap != NULL) ? heap->adapter_count() : 0;
 944 }
 945 
 946 int CodeCache::adapter_count() {
 947   int count = 0;
 948   FOR_ALL_HEAPS(heap) {
 949     count += (*heap)->adapter_count();
 950   }
 951   return count;
 952 }
 953 
 954 address CodeCache::low_bound(int code_blob_type) {
 955   CodeHeap* heap = get_code_heap(code_blob_type);
 956   return (heap != NULL) ? (address)heap->low_boundary() : NULL;
 957 }
 958 
 959 address CodeCache::high_bound(int code_blob_type) {
 960   CodeHeap* heap = get_code_heap(code_blob_type);
 961   return (heap != NULL) ? (address)heap->high_boundary() : NULL;
 962 }
 963 
 964 size_t CodeCache::capacity() {
 965   size_t cap = 0;
 966   FOR_ALL_NMETHOD_HEAPS(heap) {
 967     cap += (*heap)->capacity();
 968   }
 969   return cap;
 970 }
 971 
 972 size_t CodeCache::unallocated_capacity(int code_blob_type) {
 973   CodeHeap* heap = get_code_heap(code_blob_type);
 974   return (heap != NULL) ? heap->unallocated_capacity() : 0;
 975 }
 976 
 977 size_t CodeCache::unallocated_capacity() {
 978   size_t unallocated_cap = 0;
 979   FOR_ALL_NMETHOD_HEAPS(heap) {
 980     unallocated_cap += (*heap)->unallocated_capacity();
 981   }
 982   return unallocated_cap;
 983 }
 984 
 985 size_t CodeCache::max_capacity() {
 986   size_t max_cap = 0;
 987   FOR_ALL_NMETHOD_HEAPS(heap) {
 988     max_cap += (*heap)->max_capacity();
 989   }
 990   return max_cap;
 991 }
 992 
 993 /**
 994  * Returns the reverse free ratio. E.g., if 25% (1/4) of the code heap
 995  * is free, reverse_free_ratio() returns 4.
 996  */
 997 double CodeCache::reverse_free_ratio(int code_blob_type) {
 998   CodeHeap* heap = get_code_heap(code_blob_type);
 999   if (heap == NULL) {
1000     return 0;
1001   }
1002 
1003   double unallocated_capacity = MAX2((double)heap->unallocated_capacity(), 1.0); // Avoid division by 0;
1004   double max_capacity = (double)heap->max_capacity();
1005   double result = max_capacity / unallocated_capacity;
1006   assert (max_capacity >= unallocated_capacity, "Must be");
1007   assert (result >= 1.0, "reverse_free_ratio must be at least 1. It is %f", result);
1008   return result;
1009 }
1010 
1011 size_t CodeCache::bytes_allocated_in_freelists() {
1012   size_t allocated_bytes = 0;
1013   FOR_ALL_NMETHOD_HEAPS(heap) {
1014     allocated_bytes += (*heap)->allocated_in_freelist();
1015   }
1016   return allocated_bytes;
1017 }
1018 
1019 int CodeCache::allocated_segments() {
1020   int number_of_segments = 0;
1021   FOR_ALL_NMETHOD_HEAPS(heap) {
1022     number_of_segments += (*heap)->allocated_segments();
1023   }
1024   return number_of_segments;
1025 }
1026 
1027 size_t CodeCache::freelists_length() {
1028   size_t length = 0;
1029   FOR_ALL_NMETHOD_HEAPS(heap) {
1030     length += (*heap)->freelist_length();
1031   }
1032   return length;
1033 }
1034 
1035 void icache_init();
1036 
1037 void CodeCache::initialize() {
1038   assert(CodeCacheSegmentSize >= (uintx)CodeEntryAlignment, "CodeCacheSegmentSize must be large enough to align entry points");
1039 #ifdef COMPILER2
1040   assert(CodeCacheSegmentSize >= (uintx)OptoLoopAlignment,  "CodeCacheSegmentSize must be large enough to align inner loops");
1041 #endif
1042   assert(CodeCacheSegmentSize >= sizeof(jdouble),    "CodeCacheSegmentSize must be large enough to align constants");
1043   // This was originally just a check of the alignment, causing failure, instead, round
1044   // the code cache to the page size.  In particular, Solaris is moving to a larger
1045   // default page size.
1046   CodeCacheExpansionSize = round_to(CodeCacheExpansionSize, os::vm_page_size());
1047 
1048   if (SegmentedCodeCache) {
1049     // Use multiple code heaps
1050     initialize_heaps();
1051   } else {
1052     // Use a single code heap
1053     FLAG_SET_ERGO(uintx, NonNMethodCodeHeapSize, 0);
1054     FLAG_SET_ERGO(uintx, ProfiledCodeHeapSize, 0);
1055     FLAG_SET_ERGO(uintx, NonProfiledCodeHeapSize, 0);
1056     ReservedCodeSpace rs = reserve_heap_memory(ReservedCodeCacheSize);
1057     add_heap(rs, "CodeCache", CodeBlobType::All);
1058   }
1059 
1060   // Initialize ICache flush mechanism
1061   // This service is needed for os::register_code_area
1062   icache_init();
1063 
1064   // Give OS a chance to register generated code area.
1065   // This is used on Windows 64 bit platforms to register
1066   // Structured Exception Handlers for our generated code.
1067   os::register_code_area((char*)low_bound(), (char*)high_bound());
1068 }
1069 
1070 void codeCache_init() {
1071   CodeCache::initialize();
1072   // Load AOT libraries and add AOT code heaps.
1073   AOTLoader::initialize();
1074 }
1075 
1076 //------------------------------------------------------------------------------------------------
1077 
1078 int CodeCache::number_of_nmethods_with_dependencies() {
1079   return _number_of_nmethods_with_dependencies;
1080 }
1081 
1082 void CodeCache::clear_inline_caches() {
1083   assert_locked_or_safepoint(CodeCache_lock);
1084   CompiledMethodIterator iter;
1085   while(iter.next_alive()) {
1086     iter.method()->clear_inline_caches();
1087   }
1088 }
1089 
1090 void CodeCache::cleanup_inline_caches() {
1091   assert_locked_or_safepoint(CodeCache_lock);
1092   NMethodIterator iter;
1093   while(iter.next_alive()) {
1094     iter.method()->cleanup_inline_caches(/*clean_all=*/true);
1095   }
1096 }
1097 
1098 // Keeps track of time spent for checking dependencies
1099 NOT_PRODUCT(static elapsedTimer dependentCheckTime;)
1100 
1101 int CodeCache::mark_for_deoptimization(KlassDepChange& changes) {
1102   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1103   int number_of_marked_CodeBlobs = 0;
1104 
1105   // search the hierarchy looking for nmethods which are affected by the loading of this class
1106 
1107   // then search the interfaces this class implements looking for nmethods
1108   // which might be dependent of the fact that an interface only had one
1109   // implementor.
1110   // nmethod::check_all_dependencies works only correctly, if no safepoint
1111   // can happen
1112   NoSafepointVerifier nsv;
1113   for (DepChange::ContextStream str(changes, nsv); str.next(); ) {
1114     Klass* d = str.klass();
1115     number_of_marked_CodeBlobs += InstanceKlass::cast(d)->mark_dependent_nmethods(changes);
1116   }
1117 
1118 #ifndef PRODUCT
1119   if (VerifyDependencies) {
1120     // Object pointers are used as unique identifiers for dependency arguments. This
1121     // is only possible if no safepoint, i.e., GC occurs during the verification code.
1122     dependentCheckTime.start();
1123     nmethod::check_all_dependencies(changes);
1124     dependentCheckTime.stop();
1125   }
1126 #endif
1127 
1128   return number_of_marked_CodeBlobs;
1129 }
1130 
1131 CompiledMethod* CodeCache::find_compiled(void* start) {
1132   CodeBlob *cb = find_blob(start);
1133   assert(cb == NULL || cb->is_compiled(), "did not find an compiled_method");
1134   return (CompiledMethod*)cb;
1135 }
1136 
1137 bool CodeCache::is_far_target(address target) {
1138 #if INCLUDE_AOT
1139   return NativeCall::is_far_call(_low_bound,  target) ||
1140          NativeCall::is_far_call(_high_bound, target);
1141 #else
1142   return false;
1143 #endif
1144 }
1145 
1146 #ifdef HOTSWAP
1147 int CodeCache::mark_for_evol_deoptimization(instanceKlassHandle dependee) {
1148   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1149   int number_of_marked_CodeBlobs = 0;
1150 
1151   // Deoptimize all methods of the evolving class itself
1152   Array<Method*>* old_methods = dependee->methods();
1153   for (int i = 0; i < old_methods->length(); i++) {
1154     ResourceMark rm;
1155     Method* old_method = old_methods->at(i);
1156     CompiledMethod* nm = old_method->code();
1157     if (nm != NULL) {
1158       nm->mark_for_deoptimization();
1159       number_of_marked_CodeBlobs++;
1160     }
1161   }
1162 
1163   CompiledMethodIterator iter;
1164   while(iter.next_alive()) {
1165     CompiledMethod* nm = iter.method();
1166     if (nm->is_marked_for_deoptimization()) {
1167       // ...Already marked in the previous pass; don't count it again.
1168     } else if (nm->is_evol_dependent_on(dependee())) {
1169       ResourceMark rm;
1170       nm->mark_for_deoptimization();
1171       number_of_marked_CodeBlobs++;
1172     } else  {
1173       // flush caches in case they refer to a redefined Method*
1174       nm->clear_inline_caches();
1175     }
1176   }
1177 
1178   return number_of_marked_CodeBlobs;
1179 }
1180 #endif // HOTSWAP
1181 
1182 
1183 // Deoptimize all methods
1184 void CodeCache::mark_all_nmethods_for_deoptimization() {
1185   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1186   CompiledMethodIterator iter;
1187   while(iter.next_alive()) {
1188     CompiledMethod* nm = iter.method();
1189     if (!nm->method()->is_method_handle_intrinsic()) {
1190       nm->mark_for_deoptimization();
1191     }
1192   }
1193 }
1194 
1195 int CodeCache::mark_for_deoptimization(Method* dependee) {
1196   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1197   int number_of_marked_CodeBlobs = 0;
1198 
1199   CompiledMethodIterator iter;
1200   while(iter.next_alive()) {
1201     CompiledMethod* nm = iter.method();
1202     if (nm->is_dependent_on_method(dependee)) {
1203       ResourceMark rm;
1204       nm->mark_for_deoptimization();
1205       number_of_marked_CodeBlobs++;
1206     }
1207   }
1208 
1209   return number_of_marked_CodeBlobs;
1210 }
1211 
1212 void CodeCache::make_marked_nmethods_not_entrant() {
1213   assert_locked_or_safepoint(CodeCache_lock);
1214   CompiledMethodIterator iter;
1215   while(iter.next_alive()) {
1216     CompiledMethod* nm = iter.method();
1217     if (nm->is_marked_for_deoptimization() && !nm->is_not_entrant()) {
1218       nm->make_not_entrant();
1219     }
1220   }
1221 }
1222 
1223 // Flushes compiled methods dependent on dependee.
1224 void CodeCache::flush_dependents_on(instanceKlassHandle dependee) {
1225   assert_lock_strong(Compile_lock);
1226 
1227   if (number_of_nmethods_with_dependencies() == 0) return;
1228 
1229   // CodeCache can only be updated by a thread_in_VM and they will all be
1230   // stopped during the safepoint so CodeCache will be safe to update without
1231   // holding the CodeCache_lock.
1232 
1233   KlassDepChange changes(dependee);
1234 
1235   // Compute the dependent nmethods
1236   if (mark_for_deoptimization(changes) > 0) {
1237     // At least one nmethod has been marked for deoptimization
1238     VM_Deoptimize op;
1239     VMThread::execute(&op);
1240   }
1241 }
1242 
1243 #ifdef HOTSWAP
1244 // Flushes compiled methods dependent on dependee in the evolutionary sense
1245 void CodeCache::flush_evol_dependents_on(instanceKlassHandle ev_k_h) {
1246   // --- Compile_lock is not held. However we are at a safepoint.
1247   assert_locked_or_safepoint(Compile_lock);
1248   if (number_of_nmethods_with_dependencies() == 0 && !UseAOT) return;
1249 
1250   // CodeCache can only be updated by a thread_in_VM and they will all be
1251   // stopped during the safepoint so CodeCache will be safe to update without
1252   // holding the CodeCache_lock.
1253 
1254   // Compute the dependent nmethods
1255   if (mark_for_evol_deoptimization(ev_k_h) > 0) {
1256     // At least one nmethod has been marked for deoptimization
1257 
1258     // All this already happens inside a VM_Operation, so we'll do all the work here.
1259     // Stuff copied from VM_Deoptimize and modified slightly.
1260 
1261     // We do not want any GCs to happen while we are in the middle of this VM operation
1262     ResourceMark rm;
1263     DeoptimizationMarker dm;
1264 
1265     // Deoptimize all activations depending on marked nmethods
1266     Deoptimization::deoptimize_dependents();
1267 
1268     // Make the dependent methods not entrant
1269     make_marked_nmethods_not_entrant();
1270   }
1271 }
1272 #endif // HOTSWAP
1273 
1274 
1275 // Flushes compiled methods dependent on dependee
1276 void CodeCache::flush_dependents_on_method(methodHandle m_h) {
1277   // --- Compile_lock is not held. However we are at a safepoint.
1278   assert_locked_or_safepoint(Compile_lock);
1279 
1280   // CodeCache can only be updated by a thread_in_VM and they will all be
1281   // stopped dring the safepoint so CodeCache will be safe to update without
1282   // holding the CodeCache_lock.
1283 
1284   // Compute the dependent nmethods
1285   if (mark_for_deoptimization(m_h()) > 0) {
1286     // At least one nmethod has been marked for deoptimization
1287 
1288     // All this already happens inside a VM_Operation, so we'll do all the work here.
1289     // Stuff copied from VM_Deoptimize and modified slightly.
1290 
1291     // We do not want any GCs to happen while we are in the middle of this VM operation
1292     ResourceMark rm;
1293     DeoptimizationMarker dm;
1294 
1295     // Deoptimize all activations depending on marked nmethods
1296     Deoptimization::deoptimize_dependents();
1297 
1298     // Make the dependent methods not entrant
1299     make_marked_nmethods_not_entrant();
1300   }
1301 }
1302 
1303 void CodeCache::verify() {
1304   assert_locked_or_safepoint(CodeCache_lock);
1305   FOR_ALL_HEAPS(heap) {
1306     (*heap)->verify();
1307     FOR_ALL_BLOBS(cb, *heap) {
1308       if (cb->is_alive()) {
1309         cb->verify();
1310       }
1311     }
1312   }
1313 }
1314 
1315 // A CodeHeap is full. Print out warning and report event.
1316 void CodeCache::report_codemem_full(int code_blob_type, bool print) {
1317   // Get nmethod heap for the given CodeBlobType and build CodeCacheFull event
1318   CodeHeap* heap = get_code_heap(code_blob_type);
1319   assert(heap != NULL, "heap is null");
1320 
1321   if ((heap->full_count() == 0) || print) {
1322     // Not yet reported for this heap, report
1323     if (SegmentedCodeCache) {
1324       warning("%s is full. Compiler has been disabled.", get_code_heap_name(code_blob_type));
1325       warning("Try increasing the code heap size using -XX:%s=", get_code_heap_flag_name(code_blob_type));
1326     } else {
1327       warning("CodeCache is full. Compiler has been disabled.");
1328       warning("Try increasing the code cache size using -XX:ReservedCodeCacheSize=");
1329     }
1330     ResourceMark rm;
1331     stringStream s;
1332     // Dump code cache  into a buffer before locking the tty,
1333     {
1334       MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1335       print_summary(&s);
1336     }
1337     ttyLocker ttyl;
1338     tty->print("%s", s.as_string());
1339   }
1340 
1341   heap->report_full();
1342 
1343   EventCodeCacheFull event;
1344   if (event.should_commit()) {
1345     event.set_codeBlobType((u1)code_blob_type);
1346     event.set_startAddress((u8)heap->low_boundary());
1347     event.set_commitedTopAddress((u8)heap->high());
1348     event.set_reservedTopAddress((u8)heap->high_boundary());
1349     event.set_entryCount(heap->blob_count());
1350     event.set_methodCount(heap->nmethod_count());
1351     event.set_adaptorCount(heap->adapter_count());
1352     event.set_unallocatedCapacity(heap->unallocated_capacity());
1353     event.set_fullCount(heap->full_count());
1354     event.commit();
1355   }
1356 }
1357 
1358 void CodeCache::print_memory_overhead() {
1359   size_t wasted_bytes = 0;
1360   FOR_ALL_NMETHOD_HEAPS(heap) {
1361       CodeHeap* curr_heap = *heap;
1362       for (CodeBlob* cb = (CodeBlob*)curr_heap->first(); cb != NULL; cb = (CodeBlob*)curr_heap->next(cb)) {
1363         HeapBlock* heap_block = ((HeapBlock*)cb) - 1;
1364         wasted_bytes += heap_block->length() * CodeCacheSegmentSize - cb->size();
1365       }
1366   }
1367   // Print bytes that are allocated in the freelist
1368   ttyLocker ttl;
1369   tty->print_cr("Number of elements in freelist: " SSIZE_FORMAT,       freelists_length());
1370   tty->print_cr("Allocated in freelist:          " SSIZE_FORMAT "kB",  bytes_allocated_in_freelists()/K);
1371   tty->print_cr("Unused bytes in CodeBlobs:      " SSIZE_FORMAT "kB",  (wasted_bytes/K));
1372   tty->print_cr("Segment map size:               " SSIZE_FORMAT "kB",  allocated_segments()/K); // 1 byte per segment
1373 }
1374 
1375 //------------------------------------------------------------------------------------------------
1376 // Non-product version
1377 
1378 #ifndef PRODUCT
1379 
1380 void CodeCache::print_trace(const char* event, CodeBlob* cb, int size) {
1381   if (PrintCodeCache2) {  // Need to add a new flag
1382     ResourceMark rm;
1383     if (size == 0)  size = cb->size();
1384     tty->print_cr("CodeCache %s:  addr: " INTPTR_FORMAT ", size: 0x%x", event, p2i(cb), size);
1385   }
1386 }
1387 
1388 void CodeCache::print_internals() {
1389   int nmethodCount = 0;
1390   int runtimeStubCount = 0;
1391   int adapterCount = 0;
1392   int deoptimizationStubCount = 0;
1393   int uncommonTrapStubCount = 0;
1394   int bufferBlobCount = 0;
1395   int total = 0;
1396   int nmethodAlive = 0;
1397   int nmethodNotEntrant = 0;
1398   int nmethodZombie = 0;
1399   int nmethodUnloaded = 0;
1400   int nmethodJava = 0;
1401   int nmethodNative = 0;
1402   int max_nm_size = 0;
1403   ResourceMark rm;
1404 
1405   int i = 0;
1406   FOR_ALL_NMETHOD_HEAPS(heap) {
1407     if ((_nmethod_heaps->length() >= 1) && Verbose) {
1408       tty->print_cr("-- %s --", (*heap)->name());
1409     }
1410     FOR_ALL_BLOBS(cb, *heap) {
1411       total++;
1412       if (cb->is_nmethod()) {
1413         nmethod* nm = (nmethod*)cb;
1414 
1415         if (Verbose && nm->method() != NULL) {
1416           ResourceMark rm;
1417           char *method_name = nm->method()->name_and_sig_as_C_string();
1418           tty->print("%s", method_name);
1419           if(nm->is_alive()) { tty->print_cr(" alive"); }
1420           if(nm->is_not_entrant()) { tty->print_cr(" not-entrant"); }
1421           if(nm->is_zombie()) { tty->print_cr(" zombie"); }
1422         }
1423 
1424         nmethodCount++;
1425 
1426         if(nm->is_alive()) { nmethodAlive++; }
1427         if(nm->is_not_entrant()) { nmethodNotEntrant++; }
1428         if(nm->is_zombie()) { nmethodZombie++; }
1429         if(nm->is_unloaded()) { nmethodUnloaded++; }
1430         if(nm->method() != NULL && nm->is_native_method()) { nmethodNative++; }
1431 
1432         if(nm->method() != NULL && nm->is_java_method()) {
1433           nmethodJava++;
1434           max_nm_size = MAX2(max_nm_size, nm->size());
1435         }
1436       } else if (cb->is_runtime_stub()) {
1437         runtimeStubCount++;
1438       } else if (cb->is_deoptimization_stub()) {
1439         deoptimizationStubCount++;
1440       } else if (cb->is_uncommon_trap_stub()) {
1441         uncommonTrapStubCount++;
1442       } else if (cb->is_adapter_blob()) {
1443         adapterCount++;
1444       } else if (cb->is_buffer_blob()) {
1445         bufferBlobCount++;
1446       }
1447     }
1448   }
1449 
1450   int bucketSize = 512;
1451   int bucketLimit = max_nm_size / bucketSize + 1;
1452   int *buckets = NEW_C_HEAP_ARRAY(int, bucketLimit, mtCode);
1453   memset(buckets, 0, sizeof(int) * bucketLimit);
1454 
1455   NMethodIterator iter;
1456   while(iter.next()) {
1457     nmethod* nm = iter.method();
1458     if(nm->method() != NULL && nm->is_java_method()) {
1459       buckets[nm->size() / bucketSize]++;
1460     }
1461   }
1462 
1463   tty->print_cr("Code Cache Entries (total of %d)",total);
1464   tty->print_cr("-------------------------------------------------");
1465   tty->print_cr("nmethods: %d",nmethodCount);
1466   tty->print_cr("\talive: %d",nmethodAlive);
1467   tty->print_cr("\tnot_entrant: %d",nmethodNotEntrant);
1468   tty->print_cr("\tzombie: %d",nmethodZombie);
1469   tty->print_cr("\tunloaded: %d",nmethodUnloaded);
1470   tty->print_cr("\tjava: %d",nmethodJava);
1471   tty->print_cr("\tnative: %d",nmethodNative);
1472   tty->print_cr("runtime_stubs: %d",runtimeStubCount);
1473   tty->print_cr("adapters: %d",adapterCount);
1474   tty->print_cr("buffer blobs: %d",bufferBlobCount);
1475   tty->print_cr("deoptimization_stubs: %d",deoptimizationStubCount);
1476   tty->print_cr("uncommon_traps: %d",uncommonTrapStubCount);
1477   tty->print_cr("\nnmethod size distribution (non-zombie java)");
1478   tty->print_cr("-------------------------------------------------");
1479 
1480   for(int i=0; i<bucketLimit; i++) {
1481     if(buckets[i] != 0) {
1482       tty->print("%d - %d bytes",i*bucketSize,(i+1)*bucketSize);
1483       tty->fill_to(40);
1484       tty->print_cr("%d",buckets[i]);
1485     }
1486   }
1487 
1488   FREE_C_HEAP_ARRAY(int, buckets);
1489   print_memory_overhead();
1490 }
1491 
1492 #endif // !PRODUCT
1493 
1494 void CodeCache::print() {
1495   print_summary(tty);
1496 
1497 #ifndef PRODUCT
1498   if (!Verbose) return;
1499 
1500   CodeBlob_sizes live;
1501   CodeBlob_sizes dead;
1502 
1503   FOR_ALL_NMETHOD_HEAPS(heap) {
1504     FOR_ALL_BLOBS(cb, *heap) {
1505       if (!cb->is_alive()) {
1506         dead.add(cb);
1507       } else {
1508         live.add(cb);
1509       }
1510     }
1511   }
1512 
1513   tty->print_cr("CodeCache:");
1514   tty->print_cr("nmethod dependency checking time %fs", dependentCheckTime.seconds());
1515 
1516   if (!live.is_empty()) {
1517     live.print("live");
1518   }
1519   if (!dead.is_empty()) {
1520     dead.print("dead");
1521   }
1522 
1523   if (WizardMode) {
1524      // print the oop_map usage
1525     int code_size = 0;
1526     int number_of_blobs = 0;
1527     int number_of_oop_maps = 0;
1528     int map_size = 0;
1529     FOR_ALL_NMETHOD_HEAPS(heap) {
1530       FOR_ALL_BLOBS(cb, *heap) {
1531         if (cb->is_alive()) {
1532           number_of_blobs++;
1533           code_size += cb->code_size();
1534           ImmutableOopMapSet* set = cb->oop_maps();
1535           if (set != NULL) {
1536             number_of_oop_maps += set->count();
1537             map_size           += set->nr_of_bytes();
1538           }
1539         }
1540       }
1541     }
1542     tty->print_cr("OopMaps");
1543     tty->print_cr("  #blobs    = %d", number_of_blobs);
1544     tty->print_cr("  code size = %d", code_size);
1545     tty->print_cr("  #oop_maps = %d", number_of_oop_maps);
1546     tty->print_cr("  map size  = %d", map_size);
1547   }
1548 
1549 #endif // !PRODUCT
1550 }
1551 
1552 void CodeCache::print_summary(outputStream* st, bool detailed) {
1553   FOR_ALL_HEAPS(heap_iterator) {
1554     CodeHeap* heap = (*heap_iterator);
1555     size_t total = (heap->high_boundary() - heap->low_boundary());
1556     if (_heaps->length() >= 1) {
1557       st->print("%s:", heap->name());
1558     } else {
1559       st->print("CodeCache:");
1560     }
1561     st->print_cr(" size=" SIZE_FORMAT "Kb used=" SIZE_FORMAT
1562                  "Kb max_used=" SIZE_FORMAT "Kb free=" SIZE_FORMAT "Kb",
1563                  total/K, (total - heap->unallocated_capacity())/K,
1564                  heap->max_allocated_capacity()/K, heap->unallocated_capacity()/K);
1565 
1566     if (detailed) {
1567       st->print_cr(" bounds [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT "]",
1568                    p2i(heap->low_boundary()),
1569                    p2i(heap->high()),
1570                    p2i(heap->high_boundary()));
1571     }
1572   }
1573 
1574   if (detailed) {
1575     st->print_cr(" total_blobs=" UINT32_FORMAT " nmethods=" UINT32_FORMAT
1576                        " adapters=" UINT32_FORMAT,
1577                        blob_count(), nmethod_count(), adapter_count());
1578     st->print_cr(" compilation: %s", CompileBroker::should_compile_new_jobs() ?
1579                  "enabled" : Arguments::mode() == Arguments::_int ?
1580                  "disabled (interpreter mode)" :
1581                  "disabled (not enough contiguous free space left)");
1582   }
1583 }
1584 
1585 void CodeCache::print_codelist(outputStream* st) {
1586   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1587 
1588   NMethodIterator iter;
1589   while(iter.next_alive()) {
1590     nmethod* nm = iter.method();
1591     ResourceMark rm;
1592     char *method_name = nm->method()->name_and_sig_as_C_string();
1593     st->print_cr("%d %d %s [" INTPTR_FORMAT ", " INTPTR_FORMAT " - " INTPTR_FORMAT "]",
1594                  nm->compile_id(), nm->comp_level(), method_name, (intptr_t)nm->header_begin(),
1595                  (intptr_t)nm->code_begin(), (intptr_t)nm->code_end());
1596   }
1597 }
1598 
1599 void CodeCache::print_layout(outputStream* st) {
1600   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1601   ResourceMark rm;
1602   print_summary(st, true);
1603 }
1604 
1605 void CodeCache::log_state(outputStream* st) {
1606   st->print(" total_blobs='" UINT32_FORMAT "' nmethods='" UINT32_FORMAT "'"
1607             " adapters='" UINT32_FORMAT "' free_code_cache='" SIZE_FORMAT "'",
1608             blob_count(), nmethod_count(), adapter_count(),
1609             unallocated_capacity());
1610 }
1611