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