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