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