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