1 /*
2 * Copyright (c) 1997, 2026, 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 "asm/assembler.inline.hpp"
26 #include "cds/cdsConfig.hpp"
27 #include "code/aotCodeCache.hpp"
28 #include "code/codeCache.hpp"
29 #include "code/compiledIC.hpp"
30 #include "code/dependencies.hpp"
31 #include "code/nativeInst.hpp"
32 #include "code/nmethod.inline.hpp"
33 #include "code/scopeDesc.hpp"
34 #include "compiler/abstractCompiler.hpp"
35 #include "compiler/compilationLog.hpp"
36 #include "compiler/compileBroker.hpp"
37 #include "compiler/compileLog.hpp"
38 #include "compiler/compilerDirectives.hpp"
39 #include "compiler/compilerOracle.hpp"
40 #include "compiler/compileTask.hpp"
41 #include "compiler/directivesParser.hpp"
42 #include "compiler/disassembler.hpp"
43 #include "compiler/oopMap.inline.hpp"
44 #include "gc/shared/barrierSet.hpp"
45 #include "gc/shared/barrierSetNMethod.hpp"
46 #include "gc/shared/classUnloadingContext.hpp"
47 #include "gc/shared/collectedHeap.hpp"
48 #include "interpreter/bytecode.inline.hpp"
49 #include "jvm.h"
50 #include "logging/log.hpp"
51 #include "logging/logStream.hpp"
52 #include "memory/allocation.inline.hpp"
53 #include "memory/resourceArea.hpp"
54 #include "memory/universe.hpp"
55 #include "oops/access.inline.hpp"
56 #include "oops/klass.inline.hpp"
57 #include "oops/method.inline.hpp"
58 #include "oops/methodData.hpp"
59 #include "oops/oop.inline.hpp"
60 #include "oops/trainingData.hpp"
61 #include "oops/weakHandle.inline.hpp"
62 #include "prims/jvmtiImpl.hpp"
63 #include "prims/jvmtiThreadState.hpp"
64 #include "prims/methodHandles.hpp"
65 #include "runtime/atomicAccess.hpp"
66 #include "runtime/continuation.hpp"
67 #include "runtime/deoptimization.hpp"
68 #include "runtime/flags/flagSetting.hpp"
69 #include "runtime/frame.inline.hpp"
70 #include "runtime/handles.inline.hpp"
71 #include "runtime/jniHandles.inline.hpp"
72 #include "runtime/orderAccess.hpp"
73 #include "runtime/os.hpp"
74 #include "runtime/safepointVerifiers.hpp"
75 #include "runtime/serviceThread.hpp"
76 #include "runtime/sharedRuntime.hpp"
77 #include "runtime/signature.hpp"
78 #include "runtime/threadWXSetters.inline.hpp"
79 #include "runtime/vmThread.hpp"
80 #include "utilities/align.hpp"
81 #include "utilities/copy.hpp"
82 #include "utilities/dtrace.hpp"
83 #include "utilities/events.hpp"
84 #include "utilities/globalDefinitions.hpp"
85 #include "utilities/hashTable.hpp"
86 #include "utilities/xmlstream.hpp"
87 #if INCLUDE_JVMCI
88 #include "jvmci/jvmciRuntime.hpp"
89 #endif
90
91 #ifdef DTRACE_ENABLED
92
93 // Only bother with this argument setup if dtrace is available
94
95 #define DTRACE_METHOD_UNLOAD_PROBE(method) \
96 { \
97 Method* m = (method); \
98 if (m != nullptr) { \
99 Symbol* klass_name = m->klass_name(); \
100 Symbol* name = m->name(); \
101 Symbol* signature = m->signature(); \
102 HOTSPOT_COMPILED_METHOD_UNLOAD( \
103 (char *) klass_name->bytes(), klass_name->utf8_length(), \
104 (char *) name->bytes(), name->utf8_length(), \
105 (char *) signature->bytes(), signature->utf8_length()); \
106 } \
107 }
108
109 #else // ndef DTRACE_ENABLED
110
111 #define DTRACE_METHOD_UNLOAD_PROBE(method)
112
113 #endif
114
115 // Cast from int value to narrow type
116 #define CHECKED_CAST(result, T, thing) \
117 result = static_cast<T>(thing); \
118 guarantee(static_cast<int>(result) == thing, "failed: %d != %d", static_cast<int>(result), thing);
119
120 //---------------------------------------------------------------------------------
121 // NMethod statistics
122 // They are printed under various flags, including:
123 // PrintC1Statistics, PrintOptoStatistics, LogVMOutput, and LogCompilation.
124 // (In the latter two cases, they like other stats are printed to the log only.)
125
126 #ifndef PRODUCT
127 // These variables are put into one block to reduce relocations
128 // and make it simpler to print from the debugger.
129 struct java_nmethod_stats_struct {
130 uint nmethod_count;
131 uint total_nm_size;
132 uint total_immut_size;
133 uint total_mut_size;
134 uint relocation_size;
135 uint consts_size;
136 uint insts_size;
137 uint stub_size;
138 uint oops_size;
139 uint metadata_size;
140 uint dependencies_size;
141 uint nul_chk_table_size;
142 uint handler_table_size;
143 uint scopes_pcs_size;
144 uint scopes_data_size;
145 #if INCLUDE_JVMCI
146 uint speculations_size;
147 uint jvmci_data_size;
148 #endif
149
150 void note_nmethod(nmethod* nm) {
151 nmethod_count += 1;
152 total_nm_size += nm->size();
153 total_immut_size += nm->immutable_data_size();
154 total_mut_size += nm->mutable_data_size();
155 relocation_size += nm->relocation_size();
156 consts_size += nm->consts_size();
157 insts_size += nm->insts_size();
158 stub_size += nm->stub_size();
159 oops_size += nm->oops_size();
160 metadata_size += nm->metadata_size();
161 scopes_data_size += nm->scopes_data_size();
162 scopes_pcs_size += nm->scopes_pcs_size();
163 dependencies_size += nm->dependencies_size();
164 handler_table_size += nm->handler_table_size();
165 nul_chk_table_size += nm->nul_chk_table_size();
166 #if INCLUDE_JVMCI
167 speculations_size += nm->speculations_size();
168 jvmci_data_size += nm->jvmci_data_size();
169 #endif
170 }
171 void print_nmethod_stats(const char* name) {
172 if (nmethod_count == 0) return;
173 tty->print_cr("Statistics for %u bytecoded nmethods for %s:", nmethod_count, name);
174 uint total_size = total_nm_size + total_immut_size + total_mut_size;
175 if (total_nm_size != 0) {
176 tty->print_cr(" total size = %u (100%%)", total_size);
177 tty->print_cr(" in CodeCache = %u (%f%%)", total_nm_size, (total_nm_size * 100.0f)/total_size);
178 }
179 uint header_size = (uint)(nmethod_count * sizeof(nmethod));
180 if (nmethod_count != 0) {
181 tty->print_cr(" header = %u (%f%%)", header_size, (header_size * 100.0f)/total_nm_size);
182 }
183 if (consts_size != 0) {
184 tty->print_cr(" constants = %u (%f%%)", consts_size, (consts_size * 100.0f)/total_nm_size);
185 }
186 if (insts_size != 0) {
187 tty->print_cr(" main code = %u (%f%%)", insts_size, (insts_size * 100.0f)/total_nm_size);
188 }
189 if (stub_size != 0) {
190 tty->print_cr(" stub code = %u (%f%%)", stub_size, (stub_size * 100.0f)/total_nm_size);
191 }
192 if (oops_size != 0) {
193 tty->print_cr(" oops = %u (%f%%)", oops_size, (oops_size * 100.0f)/total_nm_size);
194 }
195 if (total_mut_size != 0) {
196 tty->print_cr(" mutable data = %u (%f%%)", total_mut_size, (total_mut_size * 100.0f)/total_size);
197 }
198 if (relocation_size != 0) {
199 tty->print_cr(" relocation = %u (%f%%)", relocation_size, (relocation_size * 100.0f)/total_mut_size);
200 }
201 if (metadata_size != 0) {
202 tty->print_cr(" metadata = %u (%f%%)", metadata_size, (metadata_size * 100.0f)/total_mut_size);
203 }
204 #if INCLUDE_JVMCI
205 if (jvmci_data_size != 0) {
206 tty->print_cr(" JVMCI data = %u (%f%%)", jvmci_data_size, (jvmci_data_size * 100.0f)/total_mut_size);
207 }
208 #endif
209 if (total_immut_size != 0) {
210 tty->print_cr(" immutable data = %u (%f%%)", total_immut_size, (total_immut_size * 100.0f)/total_size);
211 }
212 if (dependencies_size != 0) {
213 tty->print_cr(" dependencies = %u (%f%%)", dependencies_size, (dependencies_size * 100.0f)/total_immut_size);
214 }
215 if (nul_chk_table_size != 0) {
216 tty->print_cr(" nul chk table = %u (%f%%)", nul_chk_table_size, (nul_chk_table_size * 100.0f)/total_immut_size);
217 }
218 if (handler_table_size != 0) {
219 tty->print_cr(" handler table = %u (%f%%)", handler_table_size, (handler_table_size * 100.0f)/total_immut_size);
220 }
221 if (scopes_pcs_size != 0) {
222 tty->print_cr(" scopes pcs = %u (%f%%)", scopes_pcs_size, (scopes_pcs_size * 100.0f)/total_immut_size);
223 }
224 if (scopes_data_size != 0) {
225 tty->print_cr(" scopes data = %u (%f%%)", scopes_data_size, (scopes_data_size * 100.0f)/total_immut_size);
226 }
227 #if INCLUDE_JVMCI
228 if (speculations_size != 0) {
229 tty->print_cr(" speculations = %u (%f%%)", speculations_size, (speculations_size * 100.0f)/total_immut_size);
230 }
231 #endif
232 }
233 };
234
235 struct native_nmethod_stats_struct {
236 uint native_nmethod_count;
237 uint native_total_size;
238 uint native_relocation_size;
239 uint native_insts_size;
240 uint native_oops_size;
241 uint native_metadata_size;
242 void note_native_nmethod(nmethod* nm) {
243 native_nmethod_count += 1;
244 native_total_size += nm->size();
245 native_relocation_size += nm->relocation_size();
246 native_insts_size += nm->insts_size();
247 native_oops_size += nm->oops_size();
248 native_metadata_size += nm->metadata_size();
249 }
250 void print_native_nmethod_stats() {
251 if (native_nmethod_count == 0) return;
252 tty->print_cr("Statistics for %u native nmethods:", native_nmethod_count);
253 if (native_total_size != 0) tty->print_cr(" N. total size = %u", native_total_size);
254 if (native_relocation_size != 0) tty->print_cr(" N. relocation = %u", native_relocation_size);
255 if (native_insts_size != 0) tty->print_cr(" N. main code = %u", native_insts_size);
256 if (native_oops_size != 0) tty->print_cr(" N. oops = %u", native_oops_size);
257 if (native_metadata_size != 0) tty->print_cr(" N. metadata = %u", native_metadata_size);
258 }
259 };
260
261 struct pc_nmethod_stats_struct {
262 uint pc_desc_init; // number of initialization of cache (= number of caches)
263 uint pc_desc_queries; // queries to nmethod::find_pc_desc
264 uint pc_desc_approx; // number of those which have approximate true
265 uint pc_desc_repeats; // number of _pc_descs[0] hits
266 uint pc_desc_hits; // number of LRU cache hits
267 uint pc_desc_tests; // total number of PcDesc examinations
268 uint pc_desc_searches; // total number of quasi-binary search steps
269 uint pc_desc_adds; // number of LUR cache insertions
270
271 void print_pc_stats() {
272 tty->print_cr("PcDesc Statistics: %u queries, %.2f comparisons per query",
273 pc_desc_queries,
274 (double)(pc_desc_tests + pc_desc_searches)
275 / pc_desc_queries);
276 tty->print_cr(" caches=%d queries=%u/%u, hits=%u+%u, tests=%u+%u, adds=%u",
277 pc_desc_init,
278 pc_desc_queries, pc_desc_approx,
279 pc_desc_repeats, pc_desc_hits,
280 pc_desc_tests, pc_desc_searches, pc_desc_adds);
281 }
282 };
283
284 #ifdef COMPILER1
285 static java_nmethod_stats_struct c1_java_nmethod_stats;
286 #endif
287 #ifdef COMPILER2
288 static java_nmethod_stats_struct c2_java_nmethod_stats;
289 #endif
290 #if INCLUDE_JVMCI
291 static java_nmethod_stats_struct jvmci_java_nmethod_stats;
292 #endif
293 static java_nmethod_stats_struct unknown_java_nmethod_stats;
294
295 static native_nmethod_stats_struct native_nmethod_stats;
296 static pc_nmethod_stats_struct pc_nmethod_stats;
297
298 static void note_java_nmethod(nmethod* nm) {
299 #ifdef COMPILER1
300 if (nm->is_compiled_by_c1()) {
301 c1_java_nmethod_stats.note_nmethod(nm);
302 } else
303 #endif
304 #ifdef COMPILER2
305 if (nm->is_compiled_by_c2()) {
306 c2_java_nmethod_stats.note_nmethod(nm);
307 } else
308 #endif
309 #if INCLUDE_JVMCI
310 if (nm->is_compiled_by_jvmci()) {
311 jvmci_java_nmethod_stats.note_nmethod(nm);
312 } else
313 #endif
314 {
315 unknown_java_nmethod_stats.note_nmethod(nm);
316 }
317 }
318 #endif // !PRODUCT
319
320 //---------------------------------------------------------------------------------
321
322
323 ExceptionCache::ExceptionCache(Handle exception, address pc, address handler) {
324 assert(pc != nullptr, "Must be non null");
325 assert(exception.not_null(), "Must be non null");
326 assert(handler != nullptr, "Must be non null");
327
328 _count = 0;
329 _exception_type = exception->klass();
330 _next = nullptr;
331 _purge_list_next = nullptr;
332
333 add_address_and_handler(pc,handler);
334 }
335
336
337 address ExceptionCache::match(Handle exception, address pc) {
338 assert(pc != nullptr,"Must be non null");
339 assert(exception.not_null(),"Must be non null");
340 if (exception->klass() == exception_type()) {
341 return (test_address(pc));
342 }
343
344 return nullptr;
345 }
346
347
348 bool ExceptionCache::match_exception_with_space(Handle exception) {
349 assert(exception.not_null(),"Must be non null");
350 if (exception->klass() == exception_type() && count() < cache_size) {
351 return true;
352 }
353 return false;
354 }
355
356
357 address ExceptionCache::test_address(address addr) {
358 int limit = count();
359 for (int i = 0; i < limit; i++) {
360 if (pc_at(i) == addr) {
361 return handler_at(i);
362 }
363 }
364 return nullptr;
365 }
366
367
368 bool ExceptionCache::add_address_and_handler(address addr, address handler) {
369 if (test_address(addr) == handler) return true;
370
371 int index = count();
372 if (index < cache_size) {
373 set_pc_at(index, addr);
374 set_handler_at(index, handler);
375 increment_count();
376 return true;
377 }
378 return false;
379 }
380
381 ExceptionCache* ExceptionCache::next() {
382 return AtomicAccess::load(&_next);
383 }
384
385 void ExceptionCache::set_next(ExceptionCache *ec) {
386 AtomicAccess::store(&_next, ec);
387 }
388
389 //-----------------------------------------------------------------------------
390
391
392 // Helper used by both find_pc_desc methods.
393 static inline bool match_desc(PcDesc* pc, int pc_offset, bool approximate) {
394 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_tests);
395 if (!approximate) {
396 return pc->pc_offset() == pc_offset;
397 } else {
398 // Do not look before the sentinel
399 assert(pc_offset > PcDesc::lower_offset_limit, "illegal pc_offset");
400 return pc_offset <= pc->pc_offset() && (pc-1)->pc_offset() < pc_offset;
401 }
402 }
403
404 void PcDescCache::init_to(PcDesc* initial_pc_desc) {
405 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_init);
406 // initialize the cache by filling it with benign (non-null) values
407 assert(initial_pc_desc != nullptr && initial_pc_desc->pc_offset() == PcDesc::lower_offset_limit,
408 "must start with a sentinel");
409 for (int i = 0; i < cache_size; i++) {
410 _pc_descs[i] = initial_pc_desc;
411 }
412 }
413
414 PcDesc* PcDescCache::find_pc_desc(int pc_offset, bool approximate) {
415 // Note: one might think that caching the most recently
416 // read value separately would be a win, but one would be
417 // wrong. When many threads are updating it, the cache
418 // line it's in would bounce between caches, negating
419 // any benefit.
420
421 // In order to prevent race conditions do not load cache elements
422 // repeatedly, but use a local copy:
423 PcDesc* res;
424
425 // Step one: Check the most recently added value.
426 res = _pc_descs[0];
427 assert(res != nullptr, "PcDesc cache should be initialized already");
428
429 // Approximate only here since PcDescContainer::find_pc_desc() checked for exact case.
430 if (approximate && match_desc(res, pc_offset, approximate)) {
431 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_repeats);
432 return res;
433 }
434
435 // Step two: Check the rest of the LRU cache.
436 for (int i = 1; i < cache_size; ++i) {
437 res = _pc_descs[i];
438 if (res->pc_offset() < 0) break; // optimization: skip empty cache
439 if (match_desc(res, pc_offset, approximate)) {
440 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_hits);
441 return res;
442 }
443 }
444
445 // Report failure.
446 return nullptr;
447 }
448
449 void PcDescCache::add_pc_desc(PcDesc* pc_desc) {
450 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_adds);
451 // Update the LRU cache by shifting pc_desc forward.
452 for (int i = 0; i < cache_size; i++) {
453 PcDesc* next = _pc_descs[i];
454 _pc_descs[i] = pc_desc;
455 pc_desc = next;
456 }
457 }
458
459 // adjust pcs_size so that it is a multiple of both oopSize and
460 // sizeof(PcDesc) (assumes that if sizeof(PcDesc) is not a multiple
461 // of oopSize, then 2*sizeof(PcDesc) is)
462 static int adjust_pcs_size(int pcs_size) {
463 int nsize = align_up(pcs_size, oopSize);
464 if ((nsize % sizeof(PcDesc)) != 0) {
465 nsize = pcs_size + sizeof(PcDesc);
466 }
467 assert((nsize % oopSize) == 0, "correct alignment");
468 return nsize;
469 }
470
471 // Returns a string version of the method state.
472 const char* nmethod::state() const {
473 int state = get_state();
474 switch (state) {
475 case not_installed:
476 return "not installed";
477 case in_use:
478 return "in use";
479 case not_entrant:
480 return "not_entrant";
481 default:
482 fatal("unexpected method state: %d", state);
483 return nullptr;
484 }
485 }
486
487 void nmethod::set_deoptimized_done() {
488 ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
489 if (_deoptimization_status != deoptimize_done) { // can't go backwards
490 AtomicAccess::store(&_deoptimization_status, deoptimize_done);
491 }
492 }
493
494 ExceptionCache* nmethod::exception_cache_acquire() const {
495 return AtomicAccess::load_acquire(&_exception_cache);
496 }
497
498 void nmethod::add_exception_cache_entry(ExceptionCache* new_entry) {
499 assert(ExceptionCache_lock->owned_by_self(),"Must hold the ExceptionCache_lock");
500 assert(new_entry != nullptr,"Must be non null");
501 assert(new_entry->next() == nullptr, "Must be null");
502
503 for (;;) {
504 ExceptionCache *ec = exception_cache();
505 if (ec != nullptr) {
506 Klass* ex_klass = ec->exception_type();
507 if (!ex_klass->is_loader_alive()) {
508 // We must guarantee that entries are not inserted with new next pointer
509 // edges to ExceptionCache entries with dead klasses, due to bad interactions
510 // with concurrent ExceptionCache cleanup. Therefore, the inserts roll
511 // the head pointer forward to the first live ExceptionCache, so that the new
512 // next pointers always point at live ExceptionCaches, that are not removed due
513 // to concurrent ExceptionCache cleanup.
514 ExceptionCache* next = ec->next();
515 if (AtomicAccess::cmpxchg(&_exception_cache, ec, next) == ec) {
516 CodeCache::release_exception_cache(ec);
517 }
518 continue;
519 }
520 ec = exception_cache();
521 if (ec != nullptr) {
522 new_entry->set_next(ec);
523 }
524 }
525 if (AtomicAccess::cmpxchg(&_exception_cache, ec, new_entry) == ec) {
526 return;
527 }
528 }
529 }
530
531 void nmethod::clean_exception_cache() {
532 // For each nmethod, only a single thread may call this cleanup function
533 // at the same time, whether called in STW cleanup or concurrent cleanup.
534 // Note that if the GC is processing exception cache cleaning in a concurrent phase,
535 // then a single writer may contend with cleaning up the head pointer to the
536 // first ExceptionCache node that has a Klass* that is alive. That is fine,
537 // as long as there is no concurrent cleanup of next pointers from concurrent writers.
538 // And the concurrent writers do not clean up next pointers, only the head.
539 // Also note that concurrent readers will walk through Klass* pointers that are not
540 // alive. That does not cause ABA problems, because Klass* is deleted after
541 // a handshake with all threads, after all stale ExceptionCaches have been
542 // unlinked. That is also when the CodeCache::exception_cache_purge_list()
543 // is deleted, with all ExceptionCache entries that were cleaned concurrently.
544 // That similarly implies that CAS operations on ExceptionCache entries do not
545 // suffer from ABA problems as unlinking and deletion is separated by a global
546 // handshake operation.
547 ExceptionCache* prev = nullptr;
548 ExceptionCache* curr = exception_cache_acquire();
549
550 while (curr != nullptr) {
551 ExceptionCache* next = curr->next();
552
553 if (!curr->exception_type()->is_loader_alive()) {
554 if (prev == nullptr) {
555 // Try to clean head; this is contended by concurrent inserts, that
556 // both lazily clean the head, and insert entries at the head. If
557 // the CAS fails, the operation is restarted.
558 if (AtomicAccess::cmpxchg(&_exception_cache, curr, next) != curr) {
559 prev = nullptr;
560 curr = exception_cache_acquire();
561 continue;
562 }
563 } else {
564 // It is impossible to during cleanup connect the next pointer to
565 // an ExceptionCache that has not been published before a safepoint
566 // prior to the cleanup. Therefore, release is not required.
567 prev->set_next(next);
568 }
569 // prev stays the same.
570
571 CodeCache::release_exception_cache(curr);
572 } else {
573 prev = curr;
574 }
575
576 curr = next;
577 }
578 }
579
580 // public method for accessing the exception cache
581 // These are the public access methods.
582 address nmethod::handler_for_exception_and_pc(Handle exception, address pc) {
583 // We never grab a lock to read the exception cache, so we may
584 // have false negatives. This is okay, as it can only happen during
585 // the first few exception lookups for a given nmethod.
586 ExceptionCache* ec = exception_cache_acquire();
587 while (ec != nullptr) {
588 address ret_val;
589 if ((ret_val = ec->match(exception,pc)) != nullptr) {
590 return ret_val;
591 }
592 ec = ec->next();
593 }
594 return nullptr;
595 }
596
597 void nmethod::add_handler_for_exception_and_pc(Handle exception, address pc, address handler) {
598 // There are potential race conditions during exception cache updates, so we
599 // must own the ExceptionCache_lock before doing ANY modifications. Because
600 // we don't lock during reads, it is possible to have several threads attempt
601 // to update the cache with the same data. We need to check for already inserted
602 // copies of the current data before adding it.
603
604 MutexLocker ml(ExceptionCache_lock);
605 ExceptionCache* target_entry = exception_cache_entry_for_exception(exception);
606
607 if (target_entry == nullptr || !target_entry->add_address_and_handler(pc,handler)) {
608 target_entry = new ExceptionCache(exception,pc,handler);
609 add_exception_cache_entry(target_entry);
610 }
611 }
612
613 // private method for handling exception cache
614 // These methods are private, and used to manipulate the exception cache
615 // directly.
616 ExceptionCache* nmethod::exception_cache_entry_for_exception(Handle exception) {
617 ExceptionCache* ec = exception_cache_acquire();
618 while (ec != nullptr) {
619 if (ec->match_exception_with_space(exception)) {
620 return ec;
621 }
622 ec = ec->next();
623 }
624 return nullptr;
625 }
626
627 bool nmethod::is_at_poll_return(address pc) {
628 RelocIterator iter(this, pc, pc+1);
629 while (iter.next()) {
630 if (iter.type() == relocInfo::poll_return_type)
631 return true;
632 }
633 return false;
634 }
635
636
637 bool nmethod::is_at_poll_or_poll_return(address pc) {
638 RelocIterator iter(this, pc, pc+1);
639 while (iter.next()) {
640 relocInfo::relocType t = iter.type();
641 if (t == relocInfo::poll_return_type || t == relocInfo::poll_type)
642 return true;
643 }
644 return false;
645 }
646
647 void nmethod::verify_oop_relocations() {
648 // Ensure sure that the code matches the current oop values
649 RelocIterator iter(this, nullptr, nullptr);
650 while (iter.next()) {
651 if (iter.type() == relocInfo::oop_type) {
652 oop_Relocation* reloc = iter.oop_reloc();
653 if (!reloc->oop_is_immediate()) {
654 reloc->verify_oop_relocation();
655 }
656 }
657 }
658 }
659
660
661 ScopeDesc* nmethod::scope_desc_at(address pc) {
662 PcDesc* pd = pc_desc_at(pc);
663 guarantee(pd != nullptr, "scope must be present");
664 return new ScopeDesc(this, pd);
665 }
666
667 ScopeDesc* nmethod::scope_desc_near(address pc) {
668 PcDesc* pd = pc_desc_near(pc);
669 guarantee(pd != nullptr, "scope must be present");
670 return new ScopeDesc(this, pd);
671 }
672
673 address nmethod::oops_reloc_begin() const {
674 // If the method is not entrant then a JMP is plastered over the
675 // first few bytes. If an oop in the old code was there, that oop
676 // should not get GC'd. Skip the first few bytes of oops on
677 // not-entrant methods.
678 if (frame_complete_offset() != CodeOffsets::frame_never_safe &&
679 code_begin() + frame_complete_offset() >
680 verified_entry_point() + NativeJump::instruction_size)
681 {
682 // If we have a frame_complete_offset after the native jump, then there
683 // is no point trying to look for oops before that. This is a requirement
684 // for being allowed to scan oops concurrently.
685 return code_begin() + frame_complete_offset();
686 }
687
688 address low_boundary = verified_entry_point();
689 return low_boundary;
690 }
691
692 // Method that knows how to preserve outgoing arguments at call. This method must be
693 // called with a frame corresponding to a Java invoke
694 void nmethod::preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f) {
695 if (method() == nullptr) {
696 return;
697 }
698
699 // handle the case of an anchor explicitly set in continuation code that doesn't have a callee
700 JavaThread* thread = reg_map->thread();
701 if ((thread->has_last_Java_frame() && fr.sp() == thread->last_Java_sp())
702 JVMTI_ONLY(|| (method()->is_continuation_enter_intrinsic() && thread->on_monitor_waited_event()))) {
703 return;
704 }
705
706 if (!method()->is_native()) {
707 address pc = fr.pc();
708 bool has_receiver, has_appendix;
709 Symbol* signature;
710
711 // The method attached by JIT-compilers should be used, if present.
712 // Bytecode can be inaccurate in such case.
713 Method* callee = attached_method_before_pc(pc);
714 if (callee != nullptr) {
715 has_receiver = !(callee->access_flags().is_static());
716 has_appendix = false;
717 signature = callee->signature();
718 } else {
719 SimpleScopeDesc ssd(this, pc);
720
721 Bytecode_invoke call(methodHandle(Thread::current(), ssd.method()), ssd.bci());
722 has_receiver = call.has_receiver();
723 has_appendix = call.has_appendix();
724 signature = call.signature();
725 }
726
727 fr.oops_compiled_arguments_do(signature, has_receiver, has_appendix, reg_map, f);
728 } else if (method()->is_continuation_enter_intrinsic()) {
729 // This method only calls Continuation.enter()
730 Symbol* signature = vmSymbols::continuationEnter_signature();
731 fr.oops_compiled_arguments_do(signature, false, false, reg_map, f);
732 }
733 }
734
735 Method* nmethod::attached_method(address call_instr) {
736 assert(code_contains(call_instr), "not part of the nmethod");
737 RelocIterator iter(this, call_instr, call_instr + 1);
738 while (iter.next()) {
739 if (iter.addr() == call_instr) {
740 switch(iter.type()) {
741 case relocInfo::static_call_type: return iter.static_call_reloc()->method_value();
742 case relocInfo::opt_virtual_call_type: return iter.opt_virtual_call_reloc()->method_value();
743 case relocInfo::virtual_call_type: return iter.virtual_call_reloc()->method_value();
744 default: break;
745 }
746 }
747 }
748 return nullptr; // not found
749 }
750
751 Method* nmethod::attached_method_before_pc(address pc) {
752 if (NativeCall::is_call_before(pc)) {
753 NativeCall* ncall = nativeCall_before(pc);
754 return attached_method(ncall->instruction_address());
755 }
756 return nullptr; // not a call
757 }
758
759 void nmethod::clear_inline_caches() {
760 assert(SafepointSynchronize::is_at_safepoint() || (NMethodState_lock->owned_by_self() && is_not_installed()), "clearing of IC's only allowed at safepoint or when not installed");
761 RelocIterator iter(this);
762 while (iter.next()) {
763 iter.reloc()->clear_inline_cache();
764 }
765 }
766
767 #ifdef ASSERT
768 // Check class_loader is alive for this bit of metadata.
769 class CheckClass : public MetadataClosure {
770 void do_metadata(Metadata* md) {
771 Klass* klass = nullptr;
772 if (md->is_klass()) {
773 klass = ((Klass*)md);
774 } else if (md->is_method()) {
775 klass = ((Method*)md)->method_holder();
776 } else if (md->is_methodData()) {
777 klass = ((MethodData*)md)->method()->method_holder();
778 } else if (md->is_methodCounters()) {
779 klass = ((MethodCounters*)md)->method()->method_holder();
780 } else {
781 md->print();
782 ShouldNotReachHere();
783 }
784 assert(klass->is_loader_alive(), "must be alive");
785 }
786 };
787 #endif // ASSERT
788
789 // Clean references to unloaded nmethods at addr from this one, which is not unloaded.
790 template <typename CallsiteT>
791 static void clean_if_nmethod_is_unloaded(CallsiteT* callsite, bool clean_all) {
792 CodeBlob* cb = CodeCache::find_blob(callsite->destination());
793 if (!cb->is_nmethod()) {
794 return;
795 }
796 nmethod* nm = cb->as_nmethod();
797 if (clean_all || !nm->is_in_use() || nm->is_unloading() || nm->method()->code() != nm) {
798 callsite->set_to_clean();
799 }
800 }
801
802 // Cleans caches in nmethods that point to either classes that are unloaded
803 // or nmethods that are unloaded.
804 //
805 // Can be called either in parallel by G1 currently or after all
806 // nmethods are unloaded. Return postponed=true in the parallel case for
807 // inline caches found that point to nmethods that are not yet visited during
808 // the do_unloading walk.
809 void nmethod::unload_nmethod_caches(bool unloading_occurred) {
810 ResourceMark rm;
811
812 // Exception cache only needs to be called if unloading occurred
813 if (unloading_occurred) {
814 clean_exception_cache();
815 }
816
817 cleanup_inline_caches_impl(unloading_occurred, false);
818
819 #ifdef ASSERT
820 // Check that the metadata embedded in the nmethod is alive
821 CheckClass check_class;
822 metadata_do(&check_class);
823 #endif
824 }
825
826 void nmethod::run_nmethod_entry_barrier() {
827 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
828 if (bs_nm != nullptr) {
829 // We want to keep an invariant that nmethods found through iterations of a Thread's
830 // nmethods found in safepoints have gone through an entry barrier and are not armed.
831 // By calling this nmethod entry barrier, it plays along and acts
832 // like any other nmethod found on the stack of a thread (fewer surprises).
833 nmethod* nm = this;
834 bool alive = bs_nm->nmethod_entry_barrier(nm);
835 assert(alive, "should be alive");
836 }
837 }
838
839 // Only called by whitebox test
840 void nmethod::cleanup_inline_caches_whitebox() {
841 assert_locked_or_safepoint(CodeCache_lock);
842 CompiledICLocker ic_locker(this);
843 cleanup_inline_caches_impl(false /* unloading_occurred */, true /* clean_all */);
844 }
845
846 address* nmethod::orig_pc_addr(const frame* fr) {
847 return (address*) ((address)fr->unextended_sp() + orig_pc_offset());
848 }
849
850 // Called to clean up after class unloading for live nmethods
851 void nmethod::cleanup_inline_caches_impl(bool unloading_occurred, bool clean_all) {
852 assert(CompiledICLocker::is_safe(this), "mt unsafe call");
853 ResourceMark rm;
854
855 // Find all calls in an nmethod and clear the ones that point to bad nmethods.
856 RelocIterator iter(this, oops_reloc_begin());
857 bool is_in_static_stub = false;
858 while(iter.next()) {
859
860 switch (iter.type()) {
861
862 case relocInfo::virtual_call_type:
863 if (unloading_occurred) {
864 // If class unloading occurred we first clear ICs where the cached metadata
865 // is referring to an unloaded klass or method.
866 CompiledIC_at(&iter)->clean_metadata();
867 }
868
869 clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), clean_all);
870 break;
871
872 case relocInfo::opt_virtual_call_type:
873 case relocInfo::static_call_type:
874 clean_if_nmethod_is_unloaded(CompiledDirectCall::at(iter.reloc()), clean_all);
875 break;
876
877 case relocInfo::static_stub_type: {
878 is_in_static_stub = true;
879 break;
880 }
881
882 case relocInfo::metadata_type: {
883 // Only the metadata relocations contained in static/opt virtual call stubs
884 // contains the Method* passed to c2i adapters. It is the only metadata
885 // relocation that needs to be walked, as it is the one metadata relocation
886 // that violates the invariant that all metadata relocations have an oop
887 // in the compiled method (due to deferred resolution and code patching).
888
889 // This causes dead metadata to remain in compiled methods that are not
890 // unloading. Unless these slippery metadata relocations of the static
891 // stubs are at least cleared, subsequent class redefinition operations
892 // will access potentially free memory, and JavaThread execution
893 // concurrent to class unloading may call c2i adapters with dead methods.
894 if (!is_in_static_stub) {
895 // The first metadata relocation after a static stub relocation is the
896 // metadata relocation of the static stub used to pass the Method* to
897 // c2i adapters.
898 continue;
899 }
900 is_in_static_stub = false;
901 if (is_unloading()) {
902 // If the nmethod itself is dying, then it may point at dead metadata.
903 // Nobody should follow that metadata; it is strictly unsafe.
904 continue;
905 }
906 metadata_Relocation* r = iter.metadata_reloc();
907 Metadata* md = r->metadata_value();
908 if (md != nullptr && md->is_method()) {
909 Method* method = static_cast<Method*>(md);
910 if (!method->method_holder()->is_loader_alive()) {
911 AtomicAccess::store(r->metadata_addr(), (Method*)nullptr);
912
913 if (!r->metadata_is_immediate()) {
914 r->fix_metadata_relocation();
915 }
916 }
917 }
918 break;
919 }
920
921 default:
922 break;
923 }
924 }
925 }
926
927 address nmethod::continuation_for_implicit_exception(address pc, bool for_div0_check) {
928 // Exception happened outside inline-cache check code => we are inside
929 // an active nmethod => use cpc to determine a return address
930 int exception_offset = int(pc - code_begin());
931 int cont_offset = ImplicitExceptionTable(this).continuation_offset( exception_offset );
932 #ifdef ASSERT
933 if (cont_offset == 0) {
934 Thread* thread = Thread::current();
935 ResourceMark rm(thread);
936 CodeBlob* cb = CodeCache::find_blob(pc);
937 assert(cb != nullptr && cb == this, "");
938
939 // Keep tty output consistent. To avoid ttyLocker, we buffer in stream, and print all at once.
940 stringStream ss;
941 ss.print_cr("implicit exception happened at " INTPTR_FORMAT, p2i(pc));
942 print_on(&ss);
943 // Buffering to a stringStream, disable internal buffering so it's not done twice.
944 method()->print_codes_on(&ss, 0, false);
945 print_code_on(&ss);
946 print_pcs_on(&ss);
947 tty->print("%s", ss.as_string()); // print all at once
948 }
949 #endif
950 if (cont_offset == 0) {
951 // Let the normal error handling report the exception
952 return nullptr;
953 }
954 if (cont_offset == exception_offset) {
955 #if INCLUDE_JVMCI
956 Deoptimization::DeoptReason deopt_reason = for_div0_check ? Deoptimization::Reason_div0_check : Deoptimization::Reason_null_check;
957 JavaThread *thread = JavaThread::current();
958 thread->set_jvmci_implicit_exception_pc(pc);
959 thread->set_pending_deoptimization(Deoptimization::make_trap_request(deopt_reason,
960 Deoptimization::Action_reinterpret));
961 return (SharedRuntime::deopt_blob()->implicit_exception_uncommon_trap());
962 #else
963 ShouldNotReachHere();
964 #endif
965 }
966 return code_begin() + cont_offset;
967 }
968
969 class HasEvolDependency : public MetadataClosure {
970 bool _has_evol_dependency;
971 public:
972 HasEvolDependency() : _has_evol_dependency(false) {}
973 void do_metadata(Metadata* md) {
974 if (md->is_method()) {
975 Method* method = (Method*)md;
976 if (method->is_old()) {
977 _has_evol_dependency = true;
978 }
979 }
980 }
981 bool has_evol_dependency() const { return _has_evol_dependency; }
982 };
983
984 bool nmethod::has_evol_metadata() {
985 // Check the metadata in relocIter and CompiledIC and also deoptimize
986 // any nmethod that has reference to old methods.
987 HasEvolDependency check_evol;
988 metadata_do(&check_evol);
989 if (check_evol.has_evol_dependency() && log_is_enabled(Debug, redefine, class, nmethod)) {
990 ResourceMark rm;
991 log_debug(redefine, class, nmethod)
992 ("Found evol dependency of nmethod %s.%s(%s) compile_id=%d on in nmethod metadata",
993 _method->method_holder()->external_name(),
994 _method->name()->as_C_string(),
995 _method->signature()->as_C_string(),
996 compile_id());
997 }
998 return check_evol.has_evol_dependency();
999 }
1000
1001 int nmethod::total_size() const {
1002 return
1003 consts_size() +
1004 insts_size() +
1005 stub_size() +
1006 scopes_data_size() +
1007 scopes_pcs_size() +
1008 handler_table_size() +
1009 nul_chk_table_size();
1010 }
1011
1012 const char* nmethod::compile_kind() const {
1013 if (is_osr_method()) return "osr";
1014 if (preloaded()) return "AP";
1015 if (is_aot()) return "A";
1016
1017 if (method() != nullptr && is_native_method()) {
1018 if (method()->is_continuation_native_intrinsic()) {
1019 return "cnt";
1020 }
1021 return "c2n";
1022 }
1023 return "";
1024 }
1025
1026 const char* nmethod::compiler_name() const {
1027 return compilertype2name(_compiler_type);
1028 }
1029
1030 #ifdef ASSERT
1031 class CheckForOopsClosure : public OopClosure {
1032 bool _found_oop = false;
1033 public:
1034 virtual void do_oop(oop* o) { _found_oop = true; }
1035 virtual void do_oop(narrowOop* o) { _found_oop = true; }
1036 bool found_oop() { return _found_oop; }
1037 };
1038 class CheckForMetadataClosure : public MetadataClosure {
1039 bool _found_metadata = false;
1040 Metadata* _ignore = nullptr;
1041 public:
1042 CheckForMetadataClosure(Metadata* ignore) : _ignore(ignore) {}
1043 virtual void do_metadata(Metadata* md) { if (md != _ignore) _found_metadata = true; }
1044 bool found_metadata() { return _found_metadata; }
1045 };
1046
1047 static void assert_no_oops_or_metadata(nmethod* nm) {
1048 if (nm == nullptr) return;
1049 assert(nm->oop_maps() == nullptr, "expectation");
1050
1051 CheckForOopsClosure cfo;
1052 nm->oops_do(&cfo);
1053 assert(!cfo.found_oop(), "no oops allowed");
1054
1055 // We allow an exception for the own Method, but require its class to be permanent.
1056 Method* own_method = nm->method();
1057 CheckForMetadataClosure cfm(/* ignore reference to own Method */ own_method);
1058 nm->metadata_do(&cfm);
1059 assert(!cfm.found_metadata(), "no metadata allowed");
1060
1061 assert(own_method->method_holder()->class_loader_data()->is_permanent_class_loader_data(),
1062 "Method's class needs to be permanent");
1063 }
1064 #endif
1065
1066 static int required_mutable_data_size(CodeBuffer* code_buffer,
1067 int jvmci_data_size = 0) {
1068 return align_up(code_buffer->total_relocation_size(), oopSize) +
1069 align_up(code_buffer->total_metadata_size(), oopSize) +
1070 align_up(jvmci_data_size, oopSize);
1071 }
1072
1073 nmethod* nmethod::new_native_nmethod(const methodHandle& method,
1074 int compile_id,
1075 CodeBuffer *code_buffer,
1076 int vep_offset,
1077 int frame_complete,
1078 int frame_size,
1079 ByteSize basic_lock_owner_sp_offset,
1080 ByteSize basic_lock_sp_offset,
1081 OopMapSet* oop_maps,
1082 int exception_handler) {
1083 code_buffer->finalize_oop_references(method);
1084 // create nmethod
1085 nmethod* nm = nullptr;
1086 int native_nmethod_size = CodeBlob::allocation_size(code_buffer, sizeof(nmethod));
1087 {
1088 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1089
1090 CodeOffsets offsets;
1091 offsets.set_value(CodeOffsets::Verified_Entry, vep_offset);
1092 offsets.set_value(CodeOffsets::Frame_Complete, frame_complete);
1093 if (exception_handler != -1) {
1094 offsets.set_value(CodeOffsets::Exceptions, exception_handler);
1095 }
1096
1097 int mutable_data_size = required_mutable_data_size(code_buffer);
1098
1099 // MH intrinsics are dispatch stubs which are compatible with NonNMethod space.
1100 // IsUnloadingBehaviour::is_unloading needs to handle them separately.
1101 bool allow_NonNMethod_space = method->can_be_allocated_in_NonNMethod_space();
1102 nm = new (native_nmethod_size, allow_NonNMethod_space)
1103 nmethod(method(), compiler_none, native_nmethod_size,
1104 compile_id, &offsets,
1105 code_buffer, frame_size,
1106 basic_lock_owner_sp_offset,
1107 basic_lock_sp_offset,
1108 oop_maps, mutable_data_size);
1109 DEBUG_ONLY( if (allow_NonNMethod_space) assert_no_oops_or_metadata(nm); )
1110 NOT_PRODUCT(if (nm != nullptr) native_nmethod_stats.note_native_nmethod(nm));
1111 }
1112
1113 if (nm != nullptr) {
1114 // verify nmethod
1115 DEBUG_ONLY(nm->verify();) // might block
1116
1117 nm->log_new_nmethod();
1118 }
1119 return nm;
1120 }
1121
1122 void nmethod::record_nmethod_dependency() {
1123 // To make dependency checking during class loading fast, record
1124 // the nmethod dependencies in the classes it is dependent on.
1125 // This allows the dependency checking code to simply walk the
1126 // class hierarchy above the loaded class, checking only nmethods
1127 // which are dependent on those classes. The slow way is to
1128 // check every nmethod for dependencies which makes it linear in
1129 // the number of methods compiled. For applications with a lot
1130 // classes the slow way is too slow.
1131 for (Dependencies::DepStream deps(this); deps.next(); ) {
1132 if (deps.type() == Dependencies::call_site_target_value) {
1133 // CallSite dependencies are managed on per-CallSite instance basis.
1134 oop call_site = deps.argument_oop(0);
1135 MethodHandles::add_dependent_nmethod(call_site, this);
1136 } else {
1137 InstanceKlass* ik = deps.context_type();
1138 if (ik == nullptr) {
1139 continue; // ignore things like evol_method
1140 }
1141 // record this nmethod as dependent on this klass
1142 ik->add_dependent_nmethod(this);
1143 }
1144 }
1145 }
1146
1147 nmethod* nmethod::new_nmethod(const methodHandle& method,
1148 int compile_id,
1149 int entry_bci,
1150 CodeOffsets* offsets,
1151 int orig_pc_offset,
1152 DebugInformationRecorder* debug_info,
1153 Dependencies* dependencies,
1154 CodeBuffer* code_buffer, int frame_size,
1155 OopMapSet* oop_maps,
1156 ExceptionHandlerTable* handler_table,
1157 ImplicitExceptionTable* nul_chk_table,
1158 AbstractCompiler* compiler,
1159 CompLevel comp_level
1160 #if INCLUDE_JVMCI
1161 , char* speculations,
1162 int speculations_len,
1163 JVMCINMethodData* jvmci_data
1164 #endif
1165 )
1166 {
1167 assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");
1168 code_buffer->finalize_oop_references(method);
1169 // create nmethod
1170 nmethod* nm = nullptr;
1171 int nmethod_size = CodeBlob::allocation_size(code_buffer, sizeof(nmethod));
1172
1173 int immutable_data_size =
1174 adjust_pcs_size(debug_info->pcs_size())
1175 + align_up((int)dependencies->size_in_bytes(), oopSize)
1176 + align_up(handler_table->size_in_bytes() , oopSize)
1177 + align_up(nul_chk_table->size_in_bytes() , oopSize)
1178 #if INCLUDE_JVMCI
1179 + align_up(speculations_len , oopSize)
1180 #endif
1181 + align_up(debug_info->data_size() , oopSize);
1182
1183 // First, allocate space for immutable data in C heap.
1184 address immutable_data = nullptr;
1185 if (immutable_data_size > 0) {
1186 immutable_data_size += ImmutableDataRefCountSize;
1187 immutable_data = (address)os::malloc(immutable_data_size, mtCode);
1188 if (immutable_data == nullptr) {
1189 vm_exit_out_of_memory(immutable_data_size, OOM_MALLOC_ERROR, "nmethod: no space for immutable data");
1190 return nullptr;
1191 }
1192 }
1193
1194 int mutable_data_size = required_mutable_data_size(code_buffer
1195 JVMCI_ONLY(COMMA (compiler->is_jvmci() ? jvmci_data->size() : 0)));
1196
1197 {
1198 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1199
1200 nm = new (nmethod_size, comp_level)
1201 nmethod(method(), compiler->type(), nmethod_size, immutable_data_size, mutable_data_size,
1202 compile_id, entry_bci, immutable_data, offsets, orig_pc_offset,
1203 debug_info, dependencies, code_buffer, frame_size, oop_maps,
1204 handler_table, nul_chk_table, compiler, comp_level
1205 #if INCLUDE_JVMCI
1206 , speculations,
1207 speculations_len,
1208 jvmci_data
1209 #endif
1210 );
1211
1212 if (nm != nullptr) {
1213 nm->record_nmethod_dependency();
1214 NOT_PRODUCT(note_java_nmethod(nm));
1215 }
1216 }
1217 // Do verification and logging outside CodeCache_lock.
1218 if (nm != nullptr) {
1219
1220 #ifdef ASSERT
1221 LogTarget(Debug, aot, codecache, nmethod) log;
1222 if (log.is_enabled()) {
1223 LogStream out(log);
1224 out.print_cr("== new_nmethod 2");
1225 FlagSetting fs(PrintRelocations, true);
1226 nm->print_on_impl(&out);
1227 nm->decode(&out);
1228 }
1229 #endif
1230
1231 // Safepoints in nmethod::verify aren't allowed because nm hasn't been installed yet.
1232 DEBUG_ONLY(nm->verify();)
1233 nm->log_new_nmethod();
1234 }
1235 return nm;
1236 }
1237
1238 nmethod* nmethod::restore(address code_cache_buffer,
1239 const methodHandle& method,
1240 int compile_id,
1241 address reloc_data,
1242 GrowableArray<Handle>& oop_list,
1243 GrowableArray<Metadata*>& metadata_list,
1244 ImmutableOopMapSet* oop_maps,
1245 address immutable_data,
1246 GrowableArray<Handle>& reloc_imm_oop_list,
1247 GrowableArray<Metadata*>& reloc_imm_metadata_list,
1248 AOTCodeReader* aot_code_reader)
1249 {
1250 CodeBlob::restore(code_cache_buffer, "nmethod", reloc_data, oop_maps);
1251 nmethod* nm = (nmethod*)code_cache_buffer;
1252 nm->set_method(method());
1253 nm->_compile_id = compile_id;
1254 nm->_gc_epoch = CodeCache::gc_epoch();
1255 nm->set_immutable_data(immutable_data);
1256 nm->copy_values(&oop_list);
1257 nm->copy_values(&metadata_list);
1258
1259 aot_code_reader->fix_relocations(nm, &reloc_imm_oop_list, &reloc_imm_metadata_list);
1260
1261 #ifndef PRODUCT
1262 nm->asm_remarks().init();
1263 aot_code_reader->read_asm_remarks(nm->asm_remarks(), /* use_string_table */ false);
1264 nm->dbg_strings().init();
1265 aot_code_reader->read_dbg_strings(nm->dbg_strings(), /* use_string_table */ false);
1266 #endif
1267
1268 // Flush the code block
1269 ICache::invalidate_range(nm->code_begin(), nm->code_size());
1270
1271 // Create cache after PcDesc data is copied - it will be used to initialize cache
1272 nm->_pc_desc_container = new PcDescContainer(nm->scopes_pcs_begin());
1273
1274 nm->set_aot_code_entry(aot_code_reader->aot_code_entry());
1275
1276 nm->post_init();
1277 return nm;
1278 }
1279
1280 nmethod* nmethod::new_nmethod(nmethod* archived_nm,
1281 const methodHandle& method,
1282 AbstractCompiler* compiler,
1283 int compile_id,
1284 address reloc_data,
1285 GrowableArray<Handle>& oop_list,
1286 GrowableArray<Metadata*>& metadata_list,
1287 ImmutableOopMapSet* oop_maps,
1288 address immutable_data,
1289 GrowableArray<Handle>& reloc_imm_oop_list,
1290 GrowableArray<Metadata*>& reloc_imm_metadata_list,
1291 AOTCodeReader* aot_code_reader)
1292 {
1293 nmethod* nm = nullptr;
1294 int nmethod_size = archived_nm->size();
1295 // create nmethod
1296 {
1297 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1298 address code_cache_buffer = (address)CodeCache::allocate(nmethod_size, CodeCache::get_code_blob_type(archived_nm->comp_level()));
1299 if (code_cache_buffer != nullptr) {
1300 nm = archived_nm->restore(code_cache_buffer,
1301 method,
1302 compile_id,
1303 reloc_data,
1304 oop_list,
1305 metadata_list,
1306 oop_maps,
1307 immutable_data,
1308 reloc_imm_oop_list,
1309 reloc_imm_metadata_list,
1310 aot_code_reader);
1311 nm->record_nmethod_dependency();
1312 NOT_PRODUCT(note_java_nmethod(nm));
1313 }
1314 }
1315 // Do verification and logging outside CodeCache_lock.
1316 if (nm != nullptr) {
1317 #ifdef ASSERT
1318 LogTarget(Debug, aot, codecache, nmethod) log;
1319 if (log.is_enabled()) {
1320 LogStream out(log);
1321 out.print_cr("== new_nmethod 2");
1322 FlagSetting fs(PrintRelocations, true);
1323 nm->print_on_impl(&out);
1324 nm->decode(&out);
1325 }
1326 #endif
1327 // Safepoints in nmethod::verify aren't allowed because nm hasn't been installed yet.
1328 DEBUG_ONLY(nm->verify();)
1329 nm->log_new_nmethod();
1330 }
1331 return nm;
1332 }
1333
1334 // Fill in default values for various fields
1335 void nmethod::init_defaults(CodeBuffer *code_buffer, CodeOffsets* offsets) {
1336 // avoid uninitialized fields, even for short time periods
1337 _exception_cache = nullptr;
1338 _gc_data = nullptr;
1339 _oops_do_mark_link = nullptr;
1340 _compiled_ic_data = nullptr;
1341 _aot_code_entry = nullptr;
1342
1343 _is_unloading_state = 0;
1344 _state = not_installed;
1345
1346 _has_unsafe_access = 0;
1347 _has_wide_vectors = 0;
1348 _has_monitors = 0;
1349 _has_scoped_access = 0;
1350 _has_flushed_dependencies = 0;
1351 _is_unlinked = 0;
1352 _load_reported = 0; // jvmti state
1353 _preloaded = 0;
1354 _has_clinit_barriers = 0;
1355
1356 _used = false;
1357 _deoptimization_status = not_marked;
1358
1359 // SECT_CONSTS is first in code buffer so the offset should be 0.
1360 int consts_offset = code_buffer->total_offset_of(code_buffer->consts());
1361 assert(consts_offset == 0, "const_offset: %d", consts_offset);
1362
1363 _stub_offset = content_offset() + code_buffer->total_offset_of(code_buffer->stubs());
1364
1365 CHECKED_CAST(_entry_offset, uint16_t, (offsets->value(CodeOffsets::Entry)));
1366 CHECKED_CAST(_verified_entry_offset, uint16_t, (offsets->value(CodeOffsets::Verified_Entry)));
1367
1368 _skipped_instructions_size = code_buffer->total_skipped_instructions_size();
1369 }
1370
1371 // Post initialization
1372 void nmethod::post_init() {
1373 clear_unloading_state();
1374
1375 finalize_relocations();
1376
1377 // This will disarm entry barrier.
1378 Universe::heap()->register_nmethod(this);
1379 DEBUG_ONLY(Universe::heap()->verify_nmethod(this));
1380
1381 CodeCache::commit(this);
1382 }
1383
1384 // For native wrappers
1385 nmethod::nmethod(
1386 Method* method,
1387 CompilerType type,
1388 int nmethod_size,
1389 int compile_id,
1390 CodeOffsets* offsets,
1391 CodeBuffer* code_buffer,
1392 int frame_size,
1393 ByteSize basic_lock_owner_sp_offset,
1394 ByteSize basic_lock_sp_offset,
1395 OopMapSet* oop_maps,
1396 int mutable_data_size)
1397 : CodeBlob("native nmethod", CodeBlobKind::Nmethod, code_buffer, nmethod_size, sizeof(nmethod),
1398 offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps, false, mutable_data_size),
1399 _deoptimization_generation(0),
1400 _gc_epoch(CodeCache::gc_epoch()),
1401 _method(method),
1402 _native_receiver_sp_offset(basic_lock_owner_sp_offset),
1403 _native_basic_lock_sp_offset(basic_lock_sp_offset)
1404 {
1405 {
1406 DEBUG_ONLY(NoSafepointVerifier nsv;)
1407 assert_locked_or_safepoint(CodeCache_lock);
1408
1409 init_defaults(code_buffer, offsets);
1410
1411 _osr_entry_point = nullptr;
1412 _pc_desc_container = nullptr;
1413 _entry_bci = InvocationEntryBci;
1414 _compile_id = compile_id;
1415 _comp_level = CompLevel_none;
1416 _compiler_type = type;
1417 _orig_pc_offset = 0;
1418 _num_stack_arg_slots = 0;
1419
1420 if (offsets->value(CodeOffsets::Exceptions) != -1) {
1421 // Continuation enter intrinsic
1422 _exception_offset = code_offset() + offsets->value(CodeOffsets::Exceptions);
1423 } else {
1424 _exception_offset = 0;
1425 }
1426 // Native wrappers do not have deopt handlers. Make the values
1427 // something that will never match a pc like the nmethod vtable entry
1428 _deopt_handler_entry_offset = 0;
1429 _method_profiling_count = 0;
1430 _unwind_handler_offset = 0;
1431
1432 CHECKED_CAST(_oops_size, uint16_t, align_up(code_buffer->total_oop_size(), oopSize));
1433 uint16_t metadata_size;
1434 CHECKED_CAST(metadata_size, uint16_t, align_up(code_buffer->total_metadata_size(), wordSize));
1435 JVMCI_ONLY( _metadata_size = metadata_size; )
1436 assert(_mutable_data_size == _relocation_size + metadata_size,
1437 "wrong mutable data size: %d != %d + %d",
1438 _mutable_data_size, _relocation_size, metadata_size);
1439
1440 // native wrapper does not have read-only data but we need unique not null address
1441 _immutable_data = blob_end();
1442 _immutable_data_size = 0;
1443 _nul_chk_table_offset = 0;
1444 _handler_table_offset = 0;
1445 _scopes_pcs_offset = 0;
1446 _scopes_data_offset = 0;
1447 #if INCLUDE_JVMCI
1448 _speculations_offset = 0;
1449 #endif
1450 _immutable_data_ref_count_offset = 0;
1451
1452 code_buffer->copy_code_and_locs_to(this);
1453 code_buffer->copy_values_to(this);
1454
1455 post_init();
1456 }
1457
1458 if (PrintNativeNMethods || PrintDebugInfo || PrintRelocations || PrintDependencies) {
1459 ttyLocker ttyl; // keep the following output all in one block
1460 // This output goes directly to the tty, not the compiler log.
1461 // To enable tools to match it up with the compilation activity,
1462 // be sure to tag this tty output with the compile ID.
1463 if (xtty != nullptr) {
1464 xtty->begin_head("print_native_nmethod");
1465 xtty->method(_method);
1466 xtty->stamp();
1467 xtty->end_head(" address='" INTPTR_FORMAT "'", (intptr_t) this);
1468 }
1469 // Print the header part, then print the requested information.
1470 // This is both handled in decode2(), called via print_code() -> decode()
1471 if (PrintNativeNMethods) {
1472 tty->print_cr("-------------------------- Assembly (native nmethod) ---------------------------");
1473 print_code();
1474 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1475 #if defined(SUPPORT_DATA_STRUCTS)
1476 if (AbstractDisassembler::show_structs()) {
1477 if (oop_maps != nullptr) {
1478 tty->print("oop maps:"); // oop_maps->print_on(tty) outputs a cr() at the beginning
1479 oop_maps->print_on(tty);
1480 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1481 }
1482 }
1483 #endif
1484 } else {
1485 print(); // print the header part only.
1486 }
1487 #if defined(SUPPORT_DATA_STRUCTS)
1488 if (AbstractDisassembler::show_structs()) {
1489 if (PrintRelocations) {
1490 print_relocations_on(tty);
1491 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1492 }
1493 }
1494 #endif
1495 if (xtty != nullptr) {
1496 xtty->tail("print_native_nmethod");
1497 }
1498 }
1499 }
1500
1501
1502 nmethod::nmethod(const nmethod &nm) : CodeBlob(nm._name, nm._kind, nm._size, nm._header_size)
1503 {
1504
1505 if (nm._oop_maps != nullptr) {
1506 _oop_maps = nm._oop_maps->clone();
1507 } else {
1508 _oop_maps = nullptr;
1509 }
1510
1511 _size = nm._size;
1512 _relocation_size = nm._relocation_size;
1513 _content_offset = nm._content_offset;
1514 _code_offset = nm._code_offset;
1515 _data_offset = nm._data_offset;
1516 _frame_size = nm._frame_size;
1517
1518 S390_ONLY( _ctable_offset = nm._ctable_offset; )
1519
1520 _header_size = nm._header_size;
1521 _frame_complete_offset = nm._frame_complete_offset;
1522
1523 _kind = nm._kind;
1524
1525 _caller_must_gc_arguments = nm._caller_must_gc_arguments;
1526
1527 #ifndef PRODUCT
1528 _asm_remarks.share(nm._asm_remarks);
1529 _dbg_strings.share(nm._dbg_strings);
1530 #endif
1531
1532 // Allocate memory and copy mutable data to C heap
1533 _mutable_data_size = nm._mutable_data_size;
1534 if (_mutable_data_size > 0) {
1535 _mutable_data = (address)os::malloc(_mutable_data_size, mtCode);
1536 if (_mutable_data == nullptr) {
1537 vm_exit_out_of_memory(_mutable_data_size, OOM_MALLOC_ERROR, "nmethod: no space for mutable data");
1538 }
1539 memcpy(mutable_data_begin(), nm.mutable_data_begin(), nm.mutable_data_size());
1540 } else {
1541 _mutable_data = nullptr;
1542 }
1543
1544 _deoptimization_generation = 0;
1545 _gc_epoch = CodeCache::gc_epoch();
1546 _method = nm._method;
1547 _osr_link = nullptr;
1548
1549 _exception_cache = nullptr;
1550 _gc_data = nullptr;
1551 _oops_do_mark_nmethods = nullptr;
1552 _oops_do_mark_link = nullptr;
1553 _compiled_ic_data = nullptr;
1554 _aot_code_entry = nm._aot_code_entry;
1555
1556 if (nm._osr_entry_point != nullptr) {
1557 _osr_entry_point = (nm._osr_entry_point - (address) &nm) + (address) this;
1558 } else {
1559 _osr_entry_point = nullptr;
1560 }
1561
1562 _entry_offset = nm._entry_offset;
1563 _verified_entry_offset = nm._verified_entry_offset;
1564 _entry_bci = nm._entry_bci;
1565 _immutable_data_size = nm._immutable_data_size;
1566
1567 _skipped_instructions_size = nm._skipped_instructions_size;
1568 _stub_offset = nm._stub_offset;
1569 _exception_offset = nm._exception_offset;
1570 _deopt_handler_entry_offset = nm._deopt_handler_entry_offset;
1571 _unwind_handler_offset = nm._unwind_handler_offset;
1572 _num_stack_arg_slots = nm._num_stack_arg_slots;
1573 _oops_size = nm._oops_size;
1574 #if INCLUDE_JVMCI
1575 _metadata_size = nm._metadata_size;
1576 #endif
1577 _nul_chk_table_offset = nm._nul_chk_table_offset;
1578 _handler_table_offset = nm._handler_table_offset;
1579 _scopes_pcs_offset = nm._scopes_pcs_offset;
1580 _scopes_data_offset = nm._scopes_data_offset;
1581 #if INCLUDE_JVMCI
1582 _speculations_offset = nm._speculations_offset;
1583 #endif
1584 _immutable_data_ref_count_offset = nm._immutable_data_ref_count_offset;
1585
1586 // Increment number of references to immutable data to share it between nmethods
1587 if (_immutable_data_size > 0) {
1588 _immutable_data = nm._immutable_data;
1589 inc_immutable_data_ref_count();
1590 } else {
1591 _immutable_data = blob_end();
1592 }
1593
1594 _orig_pc_offset = nm._orig_pc_offset;
1595 _compile_id = nm._compile_id;
1596 _comp_level = nm._comp_level;
1597 _compiler_type = nm._compiler_type;
1598 _is_unloading_state = nm._is_unloading_state;
1599 _state = not_installed;
1600
1601 _has_unsafe_access = nm._has_unsafe_access;
1602 _has_wide_vectors = nm._has_wide_vectors;
1603 _has_monitors = nm._has_monitors;
1604 _has_scoped_access = nm._has_scoped_access;
1605 _has_flushed_dependencies = nm._has_flushed_dependencies;
1606 _is_unlinked = nm._is_unlinked;
1607 _load_reported = nm._load_reported;
1608 _preloaded = nm._preloaded;
1609 _has_clinit_barriers = nm._has_clinit_barriers;
1610
1611 _deoptimization_status = nm._deoptimization_status;
1612
1613 if (nm._pc_desc_container != nullptr) {
1614 _pc_desc_container = new PcDescContainer(scopes_pcs_begin());
1615 } else {
1616 _pc_desc_container = nullptr;
1617 }
1618
1619 // Copy nmethod contents excluding header
1620 // - Constant part (doubles, longs and floats used in nmethod)
1621 // - Code part:
1622 // - Code body
1623 // - Exception handler
1624 // - Stub code
1625 // - OOP table
1626 memcpy(consts_begin(), nm.consts_begin(), nm.data_end() - nm.consts_begin());
1627
1628 // Fix relocation
1629 RelocIterator iter(this);
1630 CodeBuffer src(&nm);
1631 CodeBuffer dst(this);
1632 while (iter.next()) {
1633 #ifdef USE_TRAMPOLINE_STUB_FIX_OWNER
1634 // After an nmethod is moved, some direct call sites may end up out of range.
1635 // CallRelocation::fix_relocation_after_move() assumes the target is always
1636 // reachable and does not check branch range. Calling it without range checks
1637 // could cause us to write an offset too large for the instruction.
1638 //
1639 // If a call site has a trampoline, we skip the normal call relocation. The
1640 // associated trampoline_stub_Relocation will handle the call and the
1641 // trampoline, including range checks and updating the branch as needed.
1642 //
1643 // If no trampoline exists, we can assume the call target is always
1644 // reachable and therefore within direct branch range, so calling
1645 // CallRelocation::fix_relocation_after_move() is safe.
1646 if (iter.reloc()->is_call()) {
1647 address trampoline = trampoline_stub_Relocation::get_trampoline_for(iter.reloc()->addr(), this);
1648 if (trampoline != nullptr) {
1649 continue;
1650 }
1651 }
1652 #endif
1653
1654 iter.reloc()->fix_relocation_after_move(&src, &dst);
1655 }
1656
1657 {
1658 MutexLocker ml(NMethodState_lock, Mutex::_no_safepoint_check_flag);
1659 clear_inline_caches();
1660 }
1661
1662 post_init();
1663 }
1664
1665 nmethod* nmethod::relocate(CodeBlobType code_blob_type) {
1666 assert(NMethodRelocation, "must enable use of function");
1667
1668 // Locks required to be held by caller to ensure the nmethod
1669 // is not modified or purged from code cache during relocation
1670 assert_lock_strong(CodeCache_lock);
1671 assert_lock_strong(Compile_lock);
1672 assert(CompiledICLocker::is_safe(this), "mt unsafe call");
1673
1674 if (!is_relocatable()) {
1675 return nullptr;
1676 }
1677
1678 run_nmethod_entry_barrier();
1679 nmethod* nm_copy = new (size(), code_blob_type) nmethod(*this);
1680
1681 if (nm_copy == nullptr) {
1682 return nullptr;
1683 }
1684
1685 // To make dependency checking during class loading fast, record
1686 // the nmethod dependencies in the classes it is dependent on.
1687 // This allows the dependency checking code to simply walk the
1688 // class hierarchy above the loaded class, checking only nmethods
1689 // which are dependent on those classes. The slow way is to
1690 // check every nmethod for dependencies which makes it linear in
1691 // the number of methods compiled. For applications with a lot
1692 // classes the slow way is too slow.
1693 for (Dependencies::DepStream deps(nm_copy); deps.next(); ) {
1694 if (deps.type() == Dependencies::call_site_target_value) {
1695 // CallSite dependencies are managed on per-CallSite instance basis.
1696 oop call_site = deps.argument_oop(0);
1697 MethodHandles::add_dependent_nmethod(call_site, nm_copy);
1698 } else {
1699 InstanceKlass* ik = deps.context_type();
1700 if (ik == nullptr) {
1701 continue; // ignore things like evol_method
1702 }
1703 // record this nmethod as dependent on this klass
1704 ik->add_dependent_nmethod(nm_copy);
1705 }
1706 }
1707
1708 MutexLocker ml_NMethodState_lock(NMethodState_lock, Mutex::_no_safepoint_check_flag);
1709
1710 // Verify the nm we copied from is still valid
1711 if (!is_marked_for_deoptimization() && is_in_use()) {
1712 assert(method() != nullptr && method()->code() == this, "should be if is in use");
1713
1714 // Attempt to start using the copy
1715 if (nm_copy->make_in_use()) {
1716 ICache::invalidate_range(nm_copy->code_begin(), nm_copy->code_size());
1717
1718 methodHandle mh(Thread::current(), nm_copy->method());
1719 nm_copy->method()->set_code(mh, nm_copy);
1720
1721 make_not_entrant(InvalidationReason::RELOCATED);
1722
1723 nm_copy->post_compiled_method_load_event();
1724
1725 nm_copy->log_relocated_nmethod(this);
1726
1727 return nm_copy;
1728 }
1729 }
1730
1731 nm_copy->make_not_used();
1732
1733 return nullptr;
1734 }
1735
1736 bool nmethod::is_relocatable() {
1737 if (!is_java_method()) {
1738 return false;
1739 }
1740
1741 if (!is_in_use()) {
1742 return false;
1743 }
1744
1745 if (is_osr_method()) {
1746 return false;
1747 }
1748
1749 if (is_marked_for_deoptimization()) {
1750 return false;
1751 }
1752
1753 #if INCLUDE_JVMCI
1754 if (jvmci_nmethod_data() != nullptr && jvmci_nmethod_data()->has_mirror()) {
1755 return false;
1756 }
1757 #endif
1758
1759 if (is_unloading()) {
1760 return false;
1761 }
1762
1763 if (has_evol_metadata()) {
1764 return false;
1765 }
1766
1767 return true;
1768 }
1769
1770 void* nmethod::operator new(size_t size, int nmethod_size, int comp_level) throw () {
1771 return CodeCache::allocate(nmethod_size, CodeCache::get_code_blob_type(comp_level));
1772 }
1773
1774 void* nmethod::operator new(size_t size, int nmethod_size, CodeBlobType code_blob_type) throw () {
1775 return CodeCache::allocate(nmethod_size, code_blob_type);
1776 }
1777
1778 void* nmethod::operator new(size_t size, int nmethod_size, bool allow_NonNMethod_space) throw () {
1779 // Try MethodNonProfiled and MethodProfiled.
1780 void* return_value = CodeCache::allocate(nmethod_size, CodeBlobType::MethodNonProfiled);
1781 if (return_value != nullptr || !allow_NonNMethod_space) return return_value;
1782 // Try NonNMethod or give up.
1783 return CodeCache::allocate(nmethod_size, CodeBlobType::NonNMethod);
1784 }
1785
1786 // For normal JIT compiled code
1787 nmethod::nmethod(
1788 Method* method,
1789 CompilerType type,
1790 int nmethod_size,
1791 int immutable_data_size,
1792 int mutable_data_size,
1793 int compile_id,
1794 int entry_bci,
1795 address immutable_data,
1796 CodeOffsets* offsets,
1797 int orig_pc_offset,
1798 DebugInformationRecorder* debug_info,
1799 Dependencies* dependencies,
1800 CodeBuffer *code_buffer,
1801 int frame_size,
1802 OopMapSet* oop_maps,
1803 ExceptionHandlerTable* handler_table,
1804 ImplicitExceptionTable* nul_chk_table,
1805 AbstractCompiler* compiler,
1806 CompLevel comp_level
1807 #if INCLUDE_JVMCI
1808 , char* speculations,
1809 int speculations_len,
1810 JVMCINMethodData* jvmci_data
1811 #endif
1812 )
1813 : CodeBlob("nmethod", CodeBlobKind::Nmethod, code_buffer, nmethod_size, sizeof(nmethod),
1814 offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps, false, mutable_data_size),
1815 _deoptimization_generation(0),
1816 _gc_epoch(CodeCache::gc_epoch()),
1817 _method(method),
1818 _osr_link(nullptr)
1819 {
1820 assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");
1821 {
1822 DEBUG_ONLY(NoSafepointVerifier nsv;)
1823 assert_locked_or_safepoint(CodeCache_lock);
1824
1825 init_defaults(code_buffer, offsets);
1826 _method_profiling_count = 0;
1827
1828 _osr_entry_point = code_begin() + offsets->value(CodeOffsets::OSR_Entry);
1829 _entry_bci = entry_bci;
1830 _compile_id = compile_id;
1831 _comp_level = comp_level;
1832 _compiler_type = type;
1833 _orig_pc_offset = orig_pc_offset;
1834
1835 _num_stack_arg_slots = entry_bci != InvocationEntryBci ? 0 : _method->constMethod()->num_stack_arg_slots();
1836
1837 set_ctable_begin(header_begin() + content_offset());
1838
1839 #if INCLUDE_JVMCI
1840 if (compiler->is_jvmci()) {
1841 // JVMCI might not produce any stub sections
1842 if (offsets->value(CodeOffsets::Exceptions) != -1) {
1843 _exception_offset = code_offset() + offsets->value(CodeOffsets::Exceptions);
1844 } else {
1845 _exception_offset = -1;
1846 }
1847 if (offsets->value(CodeOffsets::Deopt) != -1) {
1848 _deopt_handler_entry_offset = code_offset() + offsets->value(CodeOffsets::Deopt);
1849 } else {
1850 _deopt_handler_entry_offset = -1;
1851 }
1852 } else
1853 #endif
1854 {
1855 // Exception handler and deopt handler are in the stub section
1856 assert(offsets->value(CodeOffsets::Deopt ) != -1, "must be set");
1857
1858 bool has_exception_handler = (offsets->value(CodeOffsets::Exceptions) != -1);
1859 assert(has_exception_handler == (compiler->type() != compiler_c2),
1860 "C2 compiler doesn't provide exception handler stub code.");
1861 if (has_exception_handler) {
1862 _exception_offset = _stub_offset + offsets->value(CodeOffsets::Exceptions);
1863 } else {
1864 _exception_offset = -1;
1865 }
1866
1867 _deopt_handler_entry_offset = _stub_offset + offsets->value(CodeOffsets::Deopt);
1868 }
1869 if (offsets->value(CodeOffsets::UnwindHandler) != -1) {
1870 // C1 generates UnwindHandler at the end of instructions section.
1871 // Calculate positive offset as distance between the start of stubs section
1872 // (which is also the end of instructions section) and the start of the handler.
1873 int unwind_handler_offset = code_offset() + offsets->value(CodeOffsets::UnwindHandler);
1874 CHECKED_CAST(_unwind_handler_offset, int16_t, (_stub_offset - unwind_handler_offset));
1875 } else {
1876 _unwind_handler_offset = -1;
1877 }
1878
1879 CHECKED_CAST(_oops_size, uint16_t, align_up(code_buffer->total_oop_size(), oopSize));
1880 uint16_t metadata_size;
1881 CHECKED_CAST(metadata_size, uint16_t, align_up(code_buffer->total_metadata_size(), wordSize));
1882 JVMCI_ONLY( _metadata_size = metadata_size; )
1883 int jvmci_data_size = 0 JVMCI_ONLY( + align_up(compiler->is_jvmci() ? jvmci_data->size() : 0, oopSize));
1884 assert(_mutable_data_size == _relocation_size + metadata_size + jvmci_data_size,
1885 "wrong mutable data size: %d != %d + %d + %d",
1886 _mutable_data_size, _relocation_size, metadata_size, jvmci_data_size);
1887 assert(nmethod_size == data_end() - header_begin(), "wrong nmethod size: %d != %d",
1888 nmethod_size, (int)(code_end() - header_begin()));
1889
1890 _immutable_data_size = immutable_data_size;
1891 if (immutable_data_size > 0) {
1892 assert(immutable_data != nullptr, "required");
1893 _immutable_data = immutable_data;
1894 } else {
1895 // We need unique not null address
1896 _immutable_data = blob_end();
1897 }
1898 CHECKED_CAST(_nul_chk_table_offset, uint16_t, (align_up((int)dependencies->size_in_bytes(), oopSize)));
1899 CHECKED_CAST(_handler_table_offset, uint16_t, (_nul_chk_table_offset + align_up(nul_chk_table->size_in_bytes(), oopSize)));
1900 _scopes_pcs_offset = _handler_table_offset + align_up(handler_table->size_in_bytes(), oopSize);
1901 _scopes_data_offset = _scopes_pcs_offset + adjust_pcs_size(debug_info->pcs_size());
1902
1903 #if INCLUDE_JVMCI
1904 _speculations_offset = _scopes_data_offset + align_up(debug_info->data_size(), oopSize);
1905 _immutable_data_ref_count_offset = _speculations_offset + align_up(speculations_len, oopSize);
1906 #else
1907 _immutable_data_ref_count_offset = _scopes_data_offset + align_up(debug_info->data_size(), oopSize);
1908 #endif
1909 DEBUG_ONLY( int immutable_data_end_offset = _immutable_data_ref_count_offset + ImmutableDataRefCountSize; )
1910 assert(immutable_data_end_offset <= immutable_data_size, "wrong read-only data size: %d > %d",
1911 immutable_data_end_offset, immutable_data_size);
1912
1913 // Copy code and relocation info
1914 code_buffer->copy_code_and_locs_to(this);
1915 // Copy oops and metadata
1916 code_buffer->copy_values_to(this);
1917 dependencies->copy_to(this);
1918 // Copy PcDesc and ScopeDesc data
1919 debug_info->copy_to(this);
1920
1921 // Create cache after PcDesc data is copied - it will be used to initialize cache
1922 _pc_desc_container = new PcDescContainer(scopes_pcs_begin());
1923
1924 #if INCLUDE_JVMCI
1925 if (compiler->is_jvmci()) {
1926 // Initialize the JVMCINMethodData object inlined into nm
1927 jvmci_nmethod_data()->copy(jvmci_data);
1928 }
1929 #endif
1930
1931 // Copy contents of ExceptionHandlerTable to nmethod
1932 handler_table->copy_to(this);
1933 nul_chk_table->copy_to(this);
1934
1935 #if INCLUDE_JVMCI
1936 // Copy speculations to nmethod
1937 if (speculations_size() != 0) {
1938 memcpy(speculations_begin(), speculations, speculations_len);
1939 }
1940 #endif
1941 init_immutable_data_ref_count();
1942
1943 post_init();
1944
1945 // we use the information of entry points to find out if a method is
1946 // static or non static
1947 assert(compiler->is_c2() || compiler->is_jvmci() ||
1948 _method->is_static() == (entry_point() == verified_entry_point()),
1949 " entry points must be same for static methods and vice versa");
1950 }
1951 }
1952
1953 // Print a short set of xml attributes to identify this nmethod. The
1954 // output should be embedded in some other element.
1955 void nmethod::log_identity(xmlStream* log) const {
1956 assert(log->inside_attrs_or_error(), "printing attributes");
1957 log->print(" compile_id='%d'", compile_id());
1958 const char* nm_kind = compile_kind();
1959 log->print(" compile_kind='%s'", nm_kind);
1960 log->print(" compiler='%s'", compiler_name());
1961 if (TieredCompilation) {
1962 log->print(" compile_level='%d'", comp_level());
1963 }
1964 #if INCLUDE_JVMCI
1965 if (jvmci_nmethod_data() != nullptr) {
1966 const char* jvmci_name = jvmci_nmethod_data()->name();
1967 if (jvmci_name != nullptr) {
1968 log->print(" jvmci_mirror_name='");
1969 log->text("%s", jvmci_name);
1970 log->print("'");
1971 }
1972 }
1973 #endif
1974 }
1975
1976
1977 #define LOG_OFFSET(log, name) \
1978 if (p2i(name##_end()) - p2i(name##_begin())) \
1979 log->print(" " XSTR(name) "_offset='%zd'" , \
1980 p2i(name##_begin()) - p2i(this))
1981
1982
1983 void nmethod::log_new_nmethod() const {
1984 if (LogCompilation && xtty != nullptr) {
1985 ttyLocker ttyl;
1986 xtty->begin_elem("nmethod");
1987 log_identity(xtty);
1988 xtty->print(" entry='" INTPTR_FORMAT "' size='%d'", p2i(code_begin()), size());
1989 xtty->print(" address='" INTPTR_FORMAT "'", p2i(this));
1990
1991 LOG_OFFSET(xtty, relocation);
1992 LOG_OFFSET(xtty, consts);
1993 LOG_OFFSET(xtty, insts);
1994 LOG_OFFSET(xtty, stub);
1995 LOG_OFFSET(xtty, scopes_data);
1996 LOG_OFFSET(xtty, scopes_pcs);
1997 LOG_OFFSET(xtty, dependencies);
1998 LOG_OFFSET(xtty, handler_table);
1999 LOG_OFFSET(xtty, nul_chk_table);
2000 LOG_OFFSET(xtty, oops);
2001 LOG_OFFSET(xtty, metadata);
2002
2003 xtty->method(method());
2004 xtty->stamp();
2005 xtty->end_elem();
2006 }
2007 }
2008
2009
2010 void nmethod::log_relocated_nmethod(nmethod* original) const {
2011 if (LogCompilation && xtty != nullptr) {
2012 ttyLocker ttyl;
2013 xtty->begin_elem("relocated nmethod");
2014 log_identity(xtty);
2015 xtty->print(" entry='" INTPTR_FORMAT "' size='%d'", p2i(code_begin()), size());
2016
2017 const char* original_code_heap_name = CodeCache::get_code_heap_name(CodeCache::get_code_blob_type(original));
2018 xtty->print(" original_address='" INTPTR_FORMAT "'", p2i(original));
2019 xtty->print(" original_code_heap='%s'", original_code_heap_name);
2020
2021 const char* new_code_heap_name = CodeCache::get_code_heap_name(CodeCache::get_code_blob_type(this));
2022 xtty->print(" new_address='" INTPTR_FORMAT "'", p2i(this));
2023 xtty->print(" new_code_heap='%s'", new_code_heap_name);
2024
2025 LOG_OFFSET(xtty, relocation);
2026 LOG_OFFSET(xtty, consts);
2027 LOG_OFFSET(xtty, insts);
2028 LOG_OFFSET(xtty, stub);
2029 LOG_OFFSET(xtty, scopes_data);
2030 LOG_OFFSET(xtty, scopes_pcs);
2031 LOG_OFFSET(xtty, dependencies);
2032 LOG_OFFSET(xtty, handler_table);
2033 LOG_OFFSET(xtty, nul_chk_table);
2034 LOG_OFFSET(xtty, oops);
2035 LOG_OFFSET(xtty, metadata);
2036
2037 xtty->method(method());
2038 xtty->stamp();
2039 xtty->end_elem();
2040 }
2041 }
2042
2043 #undef LOG_OFFSET
2044
2045
2046 // Print out more verbose output usually for a newly created nmethod.
2047 void nmethod::print_on_with_msg(outputStream* st, const char* msg) const {
2048 if (st != nullptr) {
2049 ttyLocker ttyl;
2050 if (WizardMode) {
2051 CompileTask::print(st, this, msg, /*short_form:*/ true);
2052 st->print_cr(" (" INTPTR_FORMAT ")", p2i(this));
2053 } else {
2054 CompileTask::print(st, this, msg, /*short_form:*/ false);
2055 }
2056 }
2057 }
2058
2059 void nmethod::maybe_print_nmethod(const DirectiveSet* directive) {
2060 bool printnmethods = directive->PrintAssemblyOption || directive->PrintNMethodsOption;
2061 if (printnmethods || PrintDebugInfo || PrintRelocations || PrintDependencies || PrintExceptionHandlers) {
2062 print_nmethod(printnmethods);
2063 }
2064 }
2065
2066 void nmethod::print_nmethod(bool printmethod) {
2067 ttyLocker ttyl; // keep the following output all in one block
2068 if (xtty != nullptr) {
2069 xtty->begin_head("print_nmethod");
2070 log_identity(xtty);
2071 xtty->stamp();
2072 xtty->end_head();
2073 }
2074 // Print the header part, then print the requested information.
2075 // This is both handled in decode2().
2076 if (printmethod) {
2077 ResourceMark m;
2078 if (is_compiled_by_c1()) {
2079 tty->cr();
2080 tty->print_cr("============================= C1-compiled nmethod ==============================");
2081 }
2082 if (is_compiled_by_jvmci()) {
2083 tty->cr();
2084 tty->print_cr("=========================== JVMCI-compiled nmethod =============================");
2085 }
2086 tty->print_cr("----------------------------------- Assembly -----------------------------------");
2087 decode2(tty);
2088 #if defined(SUPPORT_DATA_STRUCTS)
2089 if (AbstractDisassembler::show_structs()) {
2090 // Print the oops from the underlying CodeBlob as well.
2091 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2092 print_oops(tty);
2093 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2094 print_metadata(tty);
2095 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2096 print_pcs_on(tty);
2097 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2098 if (oop_maps() != nullptr) {
2099 tty->print("oop maps:"); // oop_maps()->print_on(tty) outputs a cr() at the beginning
2100 oop_maps()->print_on(tty);
2101 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2102 }
2103 }
2104 #endif
2105 } else {
2106 print(); // print the header part only.
2107 }
2108
2109 #if defined(SUPPORT_DATA_STRUCTS)
2110 if (AbstractDisassembler::show_structs()) {
2111 methodHandle mh(Thread::current(), _method);
2112 if (printmethod || PrintDebugInfo || CompilerOracle::has_option(mh, CompileCommandEnum::PrintDebugInfo)) {
2113 print_scopes();
2114 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2115 }
2116 if (printmethod || PrintRelocations || CompilerOracle::has_option(mh, CompileCommandEnum::PrintRelocations)) {
2117 print_relocations_on(tty);
2118 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2119 }
2120 if (printmethod || PrintDependencies || CompilerOracle::has_option(mh, CompileCommandEnum::PrintDependencies)) {
2121 print_dependencies_on(tty);
2122 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2123 }
2124 if (printmethod || PrintExceptionHandlers) {
2125 print_handler_table();
2126 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2127 print_nul_chk_table();
2128 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2129 }
2130
2131 if (printmethod) {
2132 print_recorded_oops();
2133 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2134 print_recorded_metadata();
2135 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2136 }
2137 }
2138 #endif
2139
2140 if (xtty != nullptr) {
2141 xtty->tail("print_nmethod");
2142 }
2143 }
2144
2145
2146 // Promote one word from an assembly-time handle to a live embedded oop.
2147 inline void nmethod::initialize_immediate_oop(oop* dest, jobject handle) {
2148 if (handle == nullptr ||
2149 // As a special case, IC oops are initialized to 1 or -1.
2150 handle == (jobject) Universe::non_oop_word()) {
2151 *(void**)dest = handle;
2152 } else {
2153 *dest = JNIHandles::resolve_non_null(handle);
2154 }
2155 }
2156
2157 void nmethod::copy_values(GrowableArray<Handle>* array) {
2158 int length = array->length();
2159 assert((address)(oops_begin() + length) <= (address)oops_end(), "oops big enough");
2160 oop* dest = oops_begin();
2161 for (int index = 0 ; index < length; index++) {
2162 dest[index] = array->at(index)();
2163 }
2164 }
2165
2166 // Have to have the same name because it's called by a template
2167 void nmethod::copy_values(GrowableArray<jobject>* array) {
2168 int length = array->length();
2169 assert((address)(oops_begin() + length) <= (address)oops_end(), "oops big enough");
2170 oop* dest = oops_begin();
2171 for (int index = 0 ; index < length; index++) {
2172 initialize_immediate_oop(&dest[index], array->at(index));
2173 }
2174
2175 // Now we can fix up all the oops in the code. We need to do this
2176 // in the code because the assembler uses jobjects as placeholders.
2177 // The code and relocations have already been initialized by the
2178 // CodeBlob constructor, so it is valid even at this early point to
2179 // iterate over relocations and patch the code.
2180 fix_oop_relocations(nullptr, nullptr, /*initialize_immediates=*/ true);
2181 }
2182
2183 void nmethod::copy_values(GrowableArray<Metadata*>* array) {
2184 int length = array->length();
2185 assert((address)(metadata_begin() + length) <= (address)metadata_end(), "big enough");
2186 Metadata** dest = metadata_begin();
2187 for (int index = 0 ; index < length; index++) {
2188 dest[index] = array->at(index);
2189 }
2190 }
2191
2192 void nmethod::fix_oop_relocations(address begin, address end, bool initialize_immediates) {
2193 // re-patch all oop-bearing instructions, just in case some oops moved
2194 RelocIterator iter(this, begin, end);
2195 while (iter.next()) {
2196 if (iter.type() == relocInfo::oop_type) {
2197 oop_Relocation* reloc = iter.oop_reloc();
2198 if (initialize_immediates && reloc->oop_is_immediate()) {
2199 oop* dest = reloc->oop_addr();
2200 jobject obj = *reinterpret_cast<jobject*>(dest);
2201 initialize_immediate_oop(dest, obj);
2202 }
2203 // Refresh the oop-related bits of this instruction.
2204 reloc->fix_oop_relocation();
2205 } else if (iter.type() == relocInfo::metadata_type) {
2206 metadata_Relocation* reloc = iter.metadata_reloc();
2207 reloc->fix_metadata_relocation();
2208 }
2209 }
2210 }
2211
2212 void nmethod::create_reloc_immediates_list(JavaThread* thread, GrowableArray<Handle>& oop_list, GrowableArray<Metadata*>& metadata_list) {
2213 RelocIterator iter(this);
2214 while (iter.next()) {
2215 if (iter.type() == relocInfo::oop_type) {
2216 oop_Relocation* reloc = iter.oop_reloc();
2217 if (reloc->oop_is_immediate()) {
2218 oop dest = reloc->oop_value();
2219 Handle h(thread, dest);
2220 oop_list.append(h);
2221 }
2222 } else if (iter.type() == relocInfo::metadata_type) {
2223 metadata_Relocation* reloc = iter.metadata_reloc();
2224 if (reloc->metadata_is_immediate()) {
2225 Metadata* m = reloc->metadata_value();
2226 metadata_list.append(m);
2227 }
2228 }
2229 }
2230 }
2231
2232 static void install_post_call_nop_displacement(nmethod* nm, address pc) {
2233 NativePostCallNop* nop = nativePostCallNop_at((address) pc);
2234 intptr_t cbaddr = (intptr_t) nm;
2235 intptr_t offset = ((intptr_t) pc) - cbaddr;
2236
2237 int oopmap_slot = nm->oop_maps()->find_slot_for_offset(int((intptr_t) pc - (intptr_t) nm->code_begin()));
2238 if (oopmap_slot < 0) { // this can happen at asynchronous (non-safepoint) stackwalks
2239 log_debug(codecache)("failed to find oopmap for cb: " INTPTR_FORMAT " offset: %d", cbaddr, (int) offset);
2240 } else if (!nop->patch(oopmap_slot, offset)) {
2241 log_debug(codecache)("failed to encode %d %d", oopmap_slot, (int) offset);
2242 }
2243 }
2244
2245 void nmethod::finalize_relocations() {
2246 NoSafepointVerifier nsv;
2247
2248 GrowableArray<NativeMovConstReg*> virtual_call_data;
2249
2250 // Make sure that post call nops fill in nmethod offsets eagerly so
2251 // we don't have to race with deoptimization
2252 RelocIterator iter(this);
2253 while (iter.next()) {
2254 if (iter.type() == relocInfo::virtual_call_type) {
2255 virtual_call_Relocation* r = iter.virtual_call_reloc();
2256 NativeMovConstReg* value = nativeMovConstReg_at(r->cached_value());
2257 virtual_call_data.append(value);
2258 } else if (iter.type() == relocInfo::post_call_nop_type) {
2259 post_call_nop_Relocation* const reloc = iter.post_call_nop_reloc();
2260 address pc = reloc->addr();
2261 install_post_call_nop_displacement(this, pc);
2262 }
2263 }
2264
2265 if (virtual_call_data.length() > 0) {
2266 // We allocate a block of CompiledICData per nmethod so the GC can purge this faster.
2267 _compiled_ic_data = new CompiledICData[virtual_call_data.length()];
2268 CompiledICData* next_data = _compiled_ic_data;
2269
2270 for (NativeMovConstReg* value : virtual_call_data) {
2271 value->set_data((intptr_t)next_data);
2272 next_data++;
2273 }
2274 }
2275 }
2276
2277 void nmethod::make_deoptimized() {
2278 if (!Continuations::enabled()) {
2279 // Don't deopt this again.
2280 set_deoptimized_done();
2281 return;
2282 }
2283
2284 assert(method() == nullptr || can_be_deoptimized(), "");
2285
2286 CompiledICLocker ml(this);
2287 assert(CompiledICLocker::is_safe(this), "mt unsafe call");
2288
2289 // If post call nops have been already patched, we can just bail-out.
2290 if (has_been_deoptimized()) {
2291 return;
2292 }
2293
2294 ResourceMark rm;
2295 RelocIterator iter(this, oops_reloc_begin());
2296
2297 // Assume there will be some calls to make deoptimized.
2298 MACOS_AARCH64_ONLY(os::thread_wx_enable_write());
2299
2300 while (iter.next()) {
2301
2302 switch (iter.type()) {
2303 case relocInfo::virtual_call_type: {
2304 CompiledIC *ic = CompiledIC_at(&iter);
2305 address pc = ic->end_of_call();
2306 NativePostCallNop* nop = nativePostCallNop_at(pc);
2307 if (nop != nullptr) {
2308 nop->make_deopt();
2309 }
2310 assert(NativeDeoptInstruction::is_deopt_at(pc), "check");
2311 break;
2312 }
2313 case relocInfo::static_call_type:
2314 case relocInfo::opt_virtual_call_type: {
2315 CompiledDirectCall *csc = CompiledDirectCall::at(iter.reloc());
2316 address pc = csc->end_of_call();
2317 NativePostCallNop* nop = nativePostCallNop_at(pc);
2318 //tty->print_cr(" - static pc %p", pc);
2319 if (nop != nullptr) {
2320 nop->make_deopt();
2321 }
2322 // We can't assert here, there are some calls to stubs / runtime
2323 // that have reloc data and doesn't have a post call NOP.
2324 //assert(NativeDeoptInstruction::is_deopt_at(pc), "check");
2325 break;
2326 }
2327 default:
2328 break;
2329 }
2330 }
2331 // Don't deopt this again.
2332 set_deoptimized_done();
2333 }
2334
2335 void nmethod::verify_clean_inline_caches() {
2336 assert(CompiledICLocker::is_safe(this), "mt unsafe call");
2337
2338 ResourceMark rm;
2339 RelocIterator iter(this, oops_reloc_begin());
2340 while(iter.next()) {
2341 switch(iter.type()) {
2342 case relocInfo::virtual_call_type: {
2343 CompiledIC *ic = CompiledIC_at(&iter);
2344 CodeBlob *cb = CodeCache::find_blob(ic->destination());
2345 assert(cb != nullptr, "destination not in CodeBlob?");
2346 nmethod* nm = cb->as_nmethod_or_null();
2347 if (nm != nullptr) {
2348 // Verify that inline caches pointing to bad nmethods are clean
2349 if (!nm->is_in_use() || nm->is_unloading()) {
2350 assert(ic->is_clean(), "IC should be clean");
2351 }
2352 }
2353 break;
2354 }
2355 case relocInfo::static_call_type:
2356 case relocInfo::opt_virtual_call_type: {
2357 CompiledDirectCall *cdc = CompiledDirectCall::at(iter.reloc());
2358 CodeBlob *cb = CodeCache::find_blob(cdc->destination());
2359 assert(cb != nullptr, "destination not in CodeBlob?");
2360 nmethod* nm = cb->as_nmethod_or_null();
2361 if (nm != nullptr) {
2362 // Verify that inline caches pointing to bad nmethods are clean
2363 if (!nm->is_in_use() || nm->is_unloading() || nm->method()->code() != nm) {
2364 assert(cdc->is_clean(), "IC should be clean");
2365 }
2366 }
2367 break;
2368 }
2369 default:
2370 break;
2371 }
2372 }
2373 }
2374
2375 void nmethod::mark_as_maybe_on_stack() {
2376 MACOS_AARCH64_ONLY(os::thread_wx_enable_write());
2377 AtomicAccess::store(&_gc_epoch, CodeCache::gc_epoch());
2378 }
2379
2380 bool nmethod::is_maybe_on_stack() {
2381 // If the condition below is true, it means that the nmethod was found to
2382 // be alive the previous completed marking cycle.
2383 return AtomicAccess::load(&_gc_epoch) >= CodeCache::previous_completed_gc_marking_cycle();
2384 }
2385
2386 void nmethod::inc_decompile_count() {
2387 if (!is_compiled_by_c2() && !is_compiled_by_jvmci()) return;
2388 // Could be gated by ProfileTraps, but do not bother...
2389 #if INCLUDE_JVMCI
2390 if (jvmci_skip_profile_deopt()) {
2391 return;
2392 }
2393 #endif
2394 Method* m = method();
2395 if (m == nullptr) return;
2396 MethodData* mdo = m->method_data();
2397 if (mdo == nullptr) return;
2398 // There is a benign race here. See comments in methodData.hpp.
2399 mdo->inc_decompile_count();
2400 }
2401
2402 void nmethod::inc_method_profiling_count() {
2403 AtomicAccess::inc(&_method_profiling_count);
2404 }
2405
2406 uint64_t nmethod::method_profiling_count() {
2407 return _method_profiling_count;
2408 }
2409
2410 bool nmethod::try_transition(signed char new_state_int) {
2411 signed char new_state = new_state_int;
2412 assert_lock_strong(NMethodState_lock);
2413 signed char old_state = _state;
2414 if (old_state >= new_state) {
2415 // Ensure monotonicity of transitions.
2416 return false;
2417 }
2418 AtomicAccess::store(&_state, new_state);
2419 return true;
2420 }
2421
2422 void nmethod::invalidate_osr_method() {
2423 assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod");
2424 // Remove from list of active nmethods
2425 if (method() != nullptr) {
2426 method()->method_holder()->remove_osr_nmethod(this);
2427 }
2428 }
2429
2430 void nmethod::log_state_change(InvalidationReason invalidation_reason) const {
2431 if (LogCompilation) {
2432 if (xtty != nullptr) {
2433 ttyLocker ttyl; // keep the following output all in one block
2434 xtty->begin_elem("make_not_entrant thread='%zu' reason='%s'",
2435 os::current_thread_id(), invalidation_reason_to_string(invalidation_reason));
2436 log_identity(xtty);
2437 xtty->stamp();
2438 xtty->end_elem();
2439 }
2440 }
2441
2442 ResourceMark rm;
2443 stringStream ss(NEW_RESOURCE_ARRAY(char, 256), 256);
2444 ss.print("made not entrant: %s", invalidation_reason_to_string(invalidation_reason));
2445
2446 CompileTask::print_ul(this, ss.freeze());
2447 if (PrintCompilation) {
2448 print_on_with_msg(tty, ss.freeze());
2449 }
2450 }
2451
2452 void nmethod::unlink_from_method() {
2453 if (method() != nullptr) {
2454 method()->unlink_code(this);
2455 }
2456 }
2457
2458 // Invalidate code
2459 bool nmethod::make_not_entrant(InvalidationReason invalidation_reason, bool keep_aot_entry) {
2460 // This can be called while the system is already at a safepoint which is ok
2461 NoSafepointVerifier nsv;
2462
2463 if (is_unloading()) {
2464 // If the nmethod is unloading, then it is already not entrant through
2465 // the nmethod entry barriers. No need to do anything; GC will unload it.
2466 return false;
2467 }
2468
2469 if (AtomicAccess::load(&_state) == not_entrant) {
2470 // Avoid taking the lock if already in required state.
2471 // This is safe from races because the state is an end-state,
2472 // which the nmethod cannot back out of once entered.
2473 // No need for fencing either.
2474 return false;
2475 }
2476
2477 MACOS_AARCH64_ONLY(os::thread_wx_enable_write());
2478
2479 {
2480 // Enter critical section. Does not block for safepoint.
2481 ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
2482
2483 if (AtomicAccess::load(&_state) == not_entrant) {
2484 // another thread already performed this transition so nothing
2485 // to do, but return false to indicate this.
2486 return false;
2487 }
2488
2489 if (is_osr_method()) {
2490 // This logic is equivalent to the logic below for patching the
2491 // verified entry point of regular methods.
2492 // this effectively makes the osr nmethod not entrant
2493 invalidate_osr_method();
2494 } else {
2495 // The caller can be calling the method statically or through an inline
2496 // cache call.
2497 BarrierSet::barrier_set()->barrier_set_nmethod()->make_not_entrant(this);
2498 }
2499
2500 if (update_recompile_counts()) {
2501 // Mark the method as decompiled.
2502 inc_decompile_count();
2503 }
2504
2505 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2506 if (bs_nm == nullptr || !bs_nm->supports_entry_barrier(this)) {
2507 // If nmethod entry barriers are not supported, we won't mark
2508 // nmethods as on-stack when they become on-stack. So we
2509 // degrade to a less accurate flushing strategy, for now.
2510 mark_as_maybe_on_stack();
2511 }
2512
2513 // Change state
2514 bool success = try_transition(not_entrant);
2515 assert(success, "Transition can't fail");
2516
2517 // Log the transition once
2518 log_state_change(invalidation_reason);
2519
2520 // Remove nmethod from method.
2521 unlink_from_method();
2522
2523 if (!keep_aot_entry) {
2524 // Keep AOT code if it was simply replaced
2525 // otherwise make it not entrant too.
2526 AOTCodeCache::invalidate(_aot_code_entry);
2527 }
2528
2529 CompileBroker::log_not_entrant(this);
2530 } // leave critical region under NMethodState_lock
2531
2532 #if INCLUDE_JVMCI
2533 // Invalidate can't occur while holding the NMethodState_lock
2534 JVMCINMethodData* nmethod_data = jvmci_nmethod_data();
2535 if (nmethod_data != nullptr) {
2536 nmethod_data->invalidate_nmethod_mirror(this, invalidation_reason);
2537 }
2538 #endif
2539
2540 #ifdef ASSERT
2541 if (is_osr_method() && method() != nullptr) {
2542 // Make sure osr nmethod is invalidated, i.e. not on the list
2543 bool found = method()->method_holder()->remove_osr_nmethod(this);
2544 assert(!found, "osr nmethod should have been invalidated");
2545 }
2546 #endif
2547
2548 return true;
2549 }
2550
2551 // For concurrent GCs, there must be a handshake between unlink and flush
2552 void nmethod::unlink() {
2553 if (is_unlinked()) {
2554 // Already unlinked.
2555 return;
2556 }
2557
2558 flush_dependencies();
2559
2560 // unlink_from_method will take the NMethodState_lock.
2561 // In this case we don't strictly need it when unlinking nmethods from
2562 // the Method, because it is only concurrently unlinked by
2563 // the entry barrier, which acquires the per nmethod lock.
2564 unlink_from_method();
2565
2566 if (is_osr_method()) {
2567 invalidate_osr_method();
2568 }
2569
2570 #if INCLUDE_JVMCI
2571 // Clear the link between this nmethod and a HotSpotNmethod mirror
2572 JVMCINMethodData* nmethod_data = jvmci_nmethod_data();
2573 if (nmethod_data != nullptr) {
2574 nmethod_data->invalidate_nmethod_mirror(this, is_cold() ?
2575 nmethod::InvalidationReason::UNLOADING_COLD :
2576 nmethod::InvalidationReason::UNLOADING);
2577 }
2578 #endif
2579
2580 // Post before flushing as jmethodID is being used
2581 post_compiled_method_unload();
2582
2583 // Register for flushing when it is safe. For concurrent class unloading,
2584 // that would be after the unloading handshake, and for STW class unloading
2585 // that would be when getting back to the VM thread.
2586 ClassUnloadingContext::context()->register_unlinked_nmethod(this);
2587 }
2588
2589 void nmethod::purge(bool unregister_nmethod) {
2590
2591 MutexLocker ml(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2592
2593 // completely deallocate this method
2594 Events::log_nmethod_flush(Thread::current(), "flushing %s nmethod " INTPTR_FORMAT, compile_kind(), p2i(this));
2595
2596 LogTarget(Debug, codecache) lt;
2597 if (lt.is_enabled()) {
2598 ResourceMark rm;
2599 LogStream ls(lt);
2600 const char* method_name = method()->name()->as_C_string();
2601 const size_t codecache_capacity = CodeCache::capacity()/1024;
2602 const size_t codecache_free_space = CodeCache::unallocated_capacity(CodeCache::get_code_blob_type(this))/1024;
2603 ls.print("Flushing %s nmethod %6d/" INTPTR_FORMAT ", level=%d, cold=%d, epoch=" UINT64_FORMAT ", cold_count=" UINT64_FORMAT ". "
2604 "Cache capacity: %zuKb, free space: %zuKb. method %s (%s)",
2605 compile_kind(), _compile_id, p2i(this), _comp_level, is_cold(), _gc_epoch, CodeCache::cold_gc_count(),
2606 codecache_capacity, codecache_free_space, method_name, compiler_name());
2607 }
2608
2609 // We need to deallocate any ExceptionCache data.
2610 // Note that we do not need to grab the nmethod lock for this, it
2611 // better be thread safe if we're disposing of it!
2612 ExceptionCache* ec = exception_cache();
2613 while(ec != nullptr) {
2614 ExceptionCache* next = ec->next();
2615 delete ec;
2616 ec = next;
2617 }
2618 if (_pc_desc_container != nullptr) {
2619 delete _pc_desc_container;
2620 }
2621 if (_compiled_ic_data != nullptr) {
2622 delete[] _compiled_ic_data;
2623 }
2624
2625 if (_immutable_data != blob_end() && !AOTCodeCache::is_address_in_aot_cache((address)_oop_maps)) {
2626 // Free memory if this was the last nmethod referencing immutable data
2627 if (dec_immutable_data_ref_count() == 0) {
2628 os::free(_immutable_data);
2629 }
2630
2631 _immutable_data = blob_end(); // Valid not null address
2632 }
2633
2634 if (unregister_nmethod) {
2635 Universe::heap()->unregister_nmethod(this);
2636 }
2637 CodeCache::unregister_old_nmethod(this);
2638
2639 JVMCI_ONLY( _metadata_size = 0; )
2640 CodeBlob::purge();
2641 }
2642
2643 oop nmethod::oop_at(int index) const {
2644 if (index == 0) {
2645 return nullptr;
2646 }
2647
2648 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2649 return bs_nm->oop_load_no_keepalive(this, index);
2650 }
2651
2652 oop nmethod::oop_at_phantom(int index) const {
2653 if (index == 0) {
2654 return nullptr;
2655 }
2656
2657 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2658 return bs_nm->oop_load_phantom(this, index);
2659 }
2660
2661 //
2662 // Notify all classes this nmethod is dependent on that it is no
2663 // longer dependent.
2664
2665 void nmethod::flush_dependencies() {
2666 if (!has_flushed_dependencies()) {
2667 set_has_flushed_dependencies(true);
2668 for (Dependencies::DepStream deps(this); deps.next(); ) {
2669 if (deps.type() == Dependencies::call_site_target_value) {
2670 // CallSite dependencies are managed on per-CallSite instance basis.
2671 oop call_site = deps.argument_oop(0);
2672 MethodHandles::clean_dependency_context(call_site);
2673 } else {
2674 InstanceKlass* ik = deps.context_type();
2675 if (ik == nullptr) {
2676 continue; // ignore things like evol_method
2677 }
2678 // During GC liveness of dependee determines class that needs to be updated.
2679 // The GC may clean dependency contexts concurrently and in parallel.
2680 ik->clean_dependency_context();
2681 }
2682 }
2683 }
2684 }
2685
2686 void nmethod::post_compiled_method(CompileTask* task) {
2687 task->mark_success();
2688 task->set_nm_content_size(content_size());
2689 task->set_nm_insts_size(insts_size());
2690 task->set_nm_total_size(total_size());
2691
2692 CompileTrainingData* ctd = task->training_data();
2693 if (ctd != nullptr) {
2694 // Record inline code size during training to help inlining during production run
2695 precond(TrainingData::need_data()); // training run
2696 int inline_size = inline_instructions_size();
2697 if (inline_size < 0) inline_size = 0;
2698 ctd->set_inline_instructions_size(inline_size);
2699 }
2700
2701 // task->is_aot_load() is true only for loaded AOT code.
2702 // nmethod::_aot_code_entry is set for loaded and stored AOT code
2703 // to invalidate the entry when nmethod is deoptimized.
2704 // VerifyAOTCode is option to not store in archive AOT code.
2705 guarantee((_aot_code_entry != nullptr) || !task->is_aot_load() || VerifyAOTCode, "sanity");
2706
2707 // JVMTI -- compiled method notification (must be done outside lock)
2708 post_compiled_method_load_event();
2709
2710 if (CompilationLog::log() != nullptr) {
2711 CompilationLog::log()->log_nmethod(JavaThread::current(), this);
2712 }
2713
2714 const DirectiveSet* directive = task->directive();
2715 maybe_print_nmethod(directive);
2716 }
2717
2718 #if INCLUDE_CDS
2719 static GrowableArrayCHeap<nmethod*, mtClassShared>* _delayed_compiled_method_load_events = nullptr;
2720
2721 void nmethod::add_delayed_compiled_method_load_event(nmethod* nm) {
2722 precond(CDSConfig::is_using_aot_linked_classes());
2723 precond(!ServiceThread::has_started());
2724
2725 // We are still in single threaded stage of VM bootstrap. No need to lock.
2726 if (_delayed_compiled_method_load_events == nullptr) {
2727 _delayed_compiled_method_load_events = new GrowableArrayCHeap<nmethod*, mtClassShared>();
2728 }
2729 _delayed_compiled_method_load_events->append(nm);
2730 }
2731
2732 void nmethod::post_delayed_compiled_method_load_events() {
2733 precond(ServiceThread::has_started());
2734 if (_delayed_compiled_method_load_events != nullptr) {
2735 for (int i = 0; i < _delayed_compiled_method_load_events->length(); i++) {
2736 nmethod* nm = _delayed_compiled_method_load_events->at(i);
2737 nm->post_compiled_method_load_event();
2738 }
2739 delete _delayed_compiled_method_load_events;
2740 _delayed_compiled_method_load_events = nullptr;
2741 }
2742 }
2743 #endif
2744
2745 // ------------------------------------------------------------------
2746 // post_compiled_method_load_event
2747 // new method for install_code() path
2748 // Transfer information from compilation to jvmti
2749 void nmethod::post_compiled_method_load_event(JvmtiThreadState* state) {
2750 #if INCLUDE_CDS
2751 if (!ServiceThread::has_started()) {
2752 // With AOT-linked classes, we could compile wrappers for native methods before the
2753 // ServiceThread has been started, so we must delay the events to be posted later.
2754 assert(state == nullptr, "must be");
2755 add_delayed_compiled_method_load_event(this);
2756 return;
2757 }
2758 #endif
2759
2760 // This is a bad time for a safepoint. We don't want
2761 // this nmethod to get unloaded while we're queueing the event.
2762 NoSafepointVerifier nsv;
2763
2764 Method* m = method();
2765 HOTSPOT_COMPILED_METHOD_LOAD(
2766 (char *) m->klass_name()->bytes(),
2767 m->klass_name()->utf8_length(),
2768 (char *) m->name()->bytes(),
2769 m->name()->utf8_length(),
2770 (char *) m->signature()->bytes(),
2771 m->signature()->utf8_length(),
2772 insts_begin(), insts_size());
2773
2774
2775 if (JvmtiExport::should_post_compiled_method_load()) {
2776 // Only post unload events if load events are found.
2777 set_load_reported();
2778 // If a JavaThread hasn't been passed in, let the Service thread
2779 // (which is a real Java thread) post the event
2780 JvmtiDeferredEvent event = JvmtiDeferredEvent::compiled_method_load_event(this);
2781 if (state == nullptr) {
2782 // Execute any barrier code for this nmethod as if it's called, since
2783 // keeping it alive looks like stack walking.
2784 run_nmethod_entry_barrier();
2785 ServiceThread::enqueue_deferred_event(&event);
2786 } else {
2787 // This enters the nmethod barrier outside in the caller.
2788 state->enqueue_event(&event);
2789 }
2790 }
2791 }
2792
2793 void nmethod::post_compiled_method_unload() {
2794 assert(_method != nullptr, "just checking");
2795 DTRACE_METHOD_UNLOAD_PROBE(method());
2796
2797 // If a JVMTI agent has enabled the CompiledMethodUnload event then
2798 // post the event. The Method* will not be valid when this is freed.
2799
2800 // Don't bother posting the unload if the load event wasn't posted.
2801 if (load_reported() && JvmtiExport::should_post_compiled_method_unload()) {
2802 JvmtiDeferredEvent event =
2803 JvmtiDeferredEvent::compiled_method_unload_event(
2804 method()->jmethod_id(), insts_begin());
2805 ServiceThread::enqueue_deferred_event(&event);
2806 }
2807 }
2808
2809 // Iterate over metadata calling this function. Used by RedefineClasses
2810 void nmethod::metadata_do(MetadataClosure* f) {
2811 {
2812 // Visit all immediate references that are embedded in the instruction stream.
2813 RelocIterator iter(this, oops_reloc_begin());
2814 while (iter.next()) {
2815 if (iter.type() == relocInfo::metadata_type) {
2816 metadata_Relocation* r = iter.metadata_reloc();
2817 // In this metadata, we must only follow those metadatas directly embedded in
2818 // the code. Other metadatas (oop_index>0) are seen as part of
2819 // the metadata section below.
2820 assert(1 == (r->metadata_is_immediate()) +
2821 (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()),
2822 "metadata must be found in exactly one place");
2823 if (r->metadata_is_immediate() && r->metadata_value() != nullptr) {
2824 Metadata* md = r->metadata_value();
2825 if (md != _method) f->do_metadata(md);
2826 }
2827 } else if (iter.type() == relocInfo::virtual_call_type) {
2828 // Check compiledIC holders associated with this nmethod
2829 ResourceMark rm;
2830 CompiledIC *ic = CompiledIC_at(&iter);
2831 ic->metadata_do(f);
2832 }
2833 }
2834 }
2835
2836 // Visit the metadata section
2837 for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
2838 if (*p == Universe::non_oop_word() || *p == nullptr) continue; // skip non-oops
2839 Metadata* md = *p;
2840 f->do_metadata(md);
2841 }
2842
2843 // Visit metadata not embedded in the other places.
2844 if (_method != nullptr) f->do_metadata(_method);
2845 }
2846
2847 // Heuristic for nuking nmethods even though their oops are live.
2848 // Main purpose is to reduce code cache pressure and get rid of
2849 // nmethods that don't seem to be all that relevant any longer.
2850 bool nmethod::is_cold() {
2851 if (!MethodFlushing || is_not_installed()) {
2852 // No heuristic unloading at all
2853 return false;
2854 }
2855
2856 if (!is_maybe_on_stack() && is_not_entrant()) {
2857 // Not entrant nmethods that are not on any stack can just
2858 // be removed
2859 return true;
2860 }
2861
2862 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2863 if (bs_nm == nullptr || !bs_nm->supports_entry_barrier(this)) {
2864 // On platforms that don't support nmethod entry barriers, we can't
2865 // trust the temporal aspect of the gc epochs. So we can't detect
2866 // cold nmethods on such platforms.
2867 return false;
2868 }
2869
2870 if (!UseCodeCacheFlushing) {
2871 // Bail out if we don't heuristically remove nmethods
2872 return false;
2873 }
2874
2875 // Other code can be phased out more gradually after N GCs
2876 return CodeCache::previous_completed_gc_marking_cycle() > _gc_epoch + 2 * CodeCache::cold_gc_count();
2877 }
2878
2879 // The _is_unloading_state encodes a tuple comprising the unloading cycle
2880 // and the result of IsUnloadingBehaviour::is_unloading() for that cycle.
2881 // This is the bit layout of the _is_unloading_state byte: 00000CCU
2882 // CC refers to the cycle, which has 2 bits, and U refers to the result of
2883 // IsUnloadingBehaviour::is_unloading() for that unloading cycle.
2884
2885 class IsUnloadingState: public AllStatic {
2886 static const uint8_t _is_unloading_mask = 1;
2887 static const uint8_t _is_unloading_shift = 0;
2888 static const uint8_t _unloading_cycle_mask = 6;
2889 static const uint8_t _unloading_cycle_shift = 1;
2890
2891 static uint8_t set_is_unloading(uint8_t state, bool value) {
2892 state &= (uint8_t)~_is_unloading_mask;
2893 if (value) {
2894 state |= 1 << _is_unloading_shift;
2895 }
2896 assert(is_unloading(state) == value, "unexpected unloading cycle overflow");
2897 return state;
2898 }
2899
2900 static uint8_t set_unloading_cycle(uint8_t state, uint8_t value) {
2901 state &= (uint8_t)~_unloading_cycle_mask;
2902 state |= (uint8_t)(value << _unloading_cycle_shift);
2903 assert(unloading_cycle(state) == value, "unexpected unloading cycle overflow");
2904 return state;
2905 }
2906
2907 public:
2908 static bool is_unloading(uint8_t state) { return (state & _is_unloading_mask) >> _is_unloading_shift == 1; }
2909 static uint8_t unloading_cycle(uint8_t state) { return (state & _unloading_cycle_mask) >> _unloading_cycle_shift; }
2910
2911 static uint8_t create(bool is_unloading, uint8_t unloading_cycle) {
2912 uint8_t state = 0;
2913 state = set_is_unloading(state, is_unloading);
2914 state = set_unloading_cycle(state, unloading_cycle);
2915 return state;
2916 }
2917 };
2918
2919 bool nmethod::is_unloading() {
2920 uint8_t state = AtomicAccess::load(&_is_unloading_state);
2921 bool state_is_unloading = IsUnloadingState::is_unloading(state);
2922 if (state_is_unloading) {
2923 return true;
2924 }
2925 uint8_t state_unloading_cycle = IsUnloadingState::unloading_cycle(state);
2926 uint8_t current_cycle = CodeCache::unloading_cycle();
2927 if (state_unloading_cycle == current_cycle) {
2928 return false;
2929 }
2930
2931 // The IsUnloadingBehaviour is responsible for calculating if the nmethod
2932 // should be unloaded. This can be either because there is a dead oop,
2933 // or because is_cold() heuristically determines it is time to unload.
2934 state_unloading_cycle = current_cycle;
2935 state_is_unloading = IsUnloadingBehaviour::is_unloading(this);
2936 uint8_t new_state = IsUnloadingState::create(state_is_unloading, state_unloading_cycle);
2937
2938 MACOS_AARCH64_ONLY(os::thread_wx_enable_write());
2939
2940 // Note that if an nmethod has dead oops, everyone will agree that the
2941 // nmethod is_unloading. However, the is_cold heuristics can yield
2942 // different outcomes, so we guard the computed result with a CAS
2943 // to ensure all threads have a shared view of whether an nmethod
2944 // is_unloading or not.
2945 uint8_t found_state = AtomicAccess::cmpxchg(&_is_unloading_state, state, new_state, memory_order_relaxed);
2946
2947 if (found_state == state) {
2948 // First to change state, we win
2949 return state_is_unloading;
2950 } else {
2951 // State already set, so use it
2952 return IsUnloadingState::is_unloading(found_state);
2953 }
2954 }
2955
2956 void nmethod::clear_unloading_state() {
2957 uint8_t state = IsUnloadingState::create(false, CodeCache::unloading_cycle());
2958 AtomicAccess::store(&_is_unloading_state, state);
2959 }
2960
2961
2962 // This is called at the end of the strong tracing/marking phase of a
2963 // GC to unload an nmethod if it contains otherwise unreachable
2964 // oops or is heuristically found to be not important.
2965 void nmethod::do_unloading(bool unloading_occurred) {
2966 // Make sure the oop's ready to receive visitors
2967 if (is_unloading()) {
2968 unlink();
2969 } else {
2970 unload_nmethod_caches(unloading_occurred);
2971 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2972 if (bs_nm != nullptr) {
2973 bs_nm->disarm(this);
2974 }
2975 }
2976 }
2977
2978 void nmethod::oops_do(OopClosure* f) {
2979 // Prevent extra code cache walk for platforms that don't have immediate oops.
2980 if (relocInfo::mustIterateImmediateOopsInCode()) {
2981 RelocIterator iter(this, oops_reloc_begin());
2982
2983 while (iter.next()) {
2984 if (iter.type() == relocInfo::oop_type ) {
2985 oop_Relocation* r = iter.oop_reloc();
2986 // In this loop, we must only follow those oops directly embedded in
2987 // the code. Other oops (oop_index>0) are seen as part of scopes_oops.
2988 assert(1 == (r->oop_is_immediate()) +
2989 (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
2990 "oop must be found in exactly one place");
2991 if (r->oop_is_immediate() && r->oop_value() != nullptr) {
2992 f->do_oop(r->oop_addr());
2993 }
2994 }
2995 }
2996 }
2997
2998 // Scopes
2999 // This includes oop constants not inlined in the code stream.
3000 for (oop* p = oops_begin(); p < oops_end(); p++) {
3001 if (*p == Universe::non_oop_word()) continue; // skip non-oops
3002 f->do_oop(p);
3003 }
3004 }
3005
3006 void nmethod::follow_nmethod(OopIterateClosure* cl) {
3007 // Process oops in the nmethod
3008 oops_do(cl);
3009
3010 // CodeCache unloading support
3011 mark_as_maybe_on_stack();
3012
3013 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
3014 bs_nm->disarm(this);
3015
3016 // There's an assumption made that this function is not used by GCs that
3017 // relocate objects, and therefore we don't call fix_oop_relocations.
3018 }
3019
3020 nmethod* volatile nmethod::_oops_do_mark_nmethods;
3021
3022 void nmethod::oops_do_log_change(const char* state) {
3023 LogTarget(Trace, gc, nmethod) lt;
3024 if (lt.is_enabled()) {
3025 LogStream ls(lt);
3026 CompileTask::print(&ls, this, state, true /* short_form */);
3027 }
3028 }
3029
3030 bool nmethod::oops_do_try_claim() {
3031 if (oops_do_try_claim_weak_request()) {
3032 nmethod* result = oops_do_try_add_to_list_as_weak_done();
3033 assert(result == nullptr, "adding to global list as weak done must always succeed.");
3034 return true;
3035 }
3036 return false;
3037 }
3038
3039 bool nmethod::oops_do_try_claim_weak_request() {
3040 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
3041
3042 if ((_oops_do_mark_link == nullptr) &&
3043 (AtomicAccess::replace_if_null(&_oops_do_mark_link, mark_link(this, claim_weak_request_tag)))) {
3044 oops_do_log_change("oops_do, mark weak request");
3045 return true;
3046 }
3047 return false;
3048 }
3049
3050 void nmethod::oops_do_set_strong_done(nmethod* old_head) {
3051 _oops_do_mark_link = mark_link(old_head, claim_strong_done_tag);
3052 }
3053
3054 nmethod::oops_do_mark_link* nmethod::oops_do_try_claim_strong_done() {
3055 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
3056
3057 oops_do_mark_link* old_next = AtomicAccess::cmpxchg(&_oops_do_mark_link, mark_link(nullptr, claim_weak_request_tag), mark_link(this, claim_strong_done_tag));
3058 if (old_next == nullptr) {
3059 oops_do_log_change("oops_do, mark strong done");
3060 }
3061 return old_next;
3062 }
3063
3064 nmethod::oops_do_mark_link* nmethod::oops_do_try_add_strong_request(nmethod::oops_do_mark_link* next) {
3065 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
3066 assert(next == mark_link(this, claim_weak_request_tag), "Should be claimed as weak");
3067
3068 oops_do_mark_link* old_next = AtomicAccess::cmpxchg(&_oops_do_mark_link, next, mark_link(this, claim_strong_request_tag));
3069 if (old_next == next) {
3070 oops_do_log_change("oops_do, mark strong request");
3071 }
3072 return old_next;
3073 }
3074
3075 bool nmethod::oops_do_try_claim_weak_done_as_strong_done(nmethod::oops_do_mark_link* next) {
3076 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
3077 assert(extract_state(next) == claim_weak_done_tag, "Should be claimed as weak done");
3078
3079 oops_do_mark_link* old_next = AtomicAccess::cmpxchg(&_oops_do_mark_link, next, mark_link(extract_nmethod(next), claim_strong_done_tag));
3080 if (old_next == next) {
3081 oops_do_log_change("oops_do, mark weak done -> mark strong done");
3082 return true;
3083 }
3084 return false;
3085 }
3086
3087 nmethod* nmethod::oops_do_try_add_to_list_as_weak_done() {
3088 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
3089
3090 assert(extract_state(_oops_do_mark_link) == claim_weak_request_tag ||
3091 extract_state(_oops_do_mark_link) == claim_strong_request_tag,
3092 "must be but is nmethod " PTR_FORMAT " %u", p2i(extract_nmethod(_oops_do_mark_link)), extract_state(_oops_do_mark_link));
3093
3094 nmethod* old_head = AtomicAccess::xchg(&_oops_do_mark_nmethods, this);
3095 // Self-loop if needed.
3096 if (old_head == nullptr) {
3097 old_head = this;
3098 }
3099 // Try to install end of list and weak done tag.
3100 if (AtomicAccess::cmpxchg(&_oops_do_mark_link, mark_link(this, claim_weak_request_tag), mark_link(old_head, claim_weak_done_tag)) == mark_link(this, claim_weak_request_tag)) {
3101 oops_do_log_change("oops_do, mark weak done");
3102 return nullptr;
3103 } else {
3104 return old_head;
3105 }
3106 }
3107
3108 void nmethod::oops_do_add_to_list_as_strong_done() {
3109 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
3110
3111 nmethod* old_head = AtomicAccess::xchg(&_oops_do_mark_nmethods, this);
3112 // Self-loop if needed.
3113 if (old_head == nullptr) {
3114 old_head = this;
3115 }
3116 assert(_oops_do_mark_link == mark_link(this, claim_strong_done_tag), "must be but is nmethod " PTR_FORMAT " state %u",
3117 p2i(extract_nmethod(_oops_do_mark_link)), extract_state(_oops_do_mark_link));
3118
3119 oops_do_set_strong_done(old_head);
3120 }
3121
3122 void nmethod::oops_do_process_weak(OopsDoProcessor* p) {
3123 if (!oops_do_try_claim_weak_request()) {
3124 // Failed to claim for weak processing.
3125 oops_do_log_change("oops_do, mark weak request fail");
3126 return;
3127 }
3128
3129 p->do_regular_processing(this);
3130
3131 nmethod* old_head = oops_do_try_add_to_list_as_weak_done();
3132 if (old_head == nullptr) {
3133 return;
3134 }
3135 oops_do_log_change("oops_do, mark weak done fail");
3136 // Adding to global list failed, another thread added a strong request.
3137 assert(extract_state(_oops_do_mark_link) == claim_strong_request_tag,
3138 "must be but is %u", extract_state(_oops_do_mark_link));
3139
3140 oops_do_log_change("oops_do, mark weak request -> mark strong done");
3141
3142 oops_do_set_strong_done(old_head);
3143 // Do missing strong processing.
3144 p->do_remaining_strong_processing(this);
3145 }
3146
3147 void nmethod::oops_do_process_strong(OopsDoProcessor* p) {
3148 oops_do_mark_link* next_raw = oops_do_try_claim_strong_done();
3149 if (next_raw == nullptr) {
3150 p->do_regular_processing(this);
3151 oops_do_add_to_list_as_strong_done();
3152 return;
3153 }
3154 // Claim failed. Figure out why and handle it.
3155 if (oops_do_has_weak_request(next_raw)) {
3156 oops_do_mark_link* old = next_raw;
3157 // Claim failed because being weak processed (state == "weak request").
3158 // Try to request deferred strong processing.
3159 next_raw = oops_do_try_add_strong_request(old);
3160 if (next_raw == old) {
3161 // Successfully requested deferred strong processing.
3162 return;
3163 }
3164 // Failed because of a concurrent transition. No longer in "weak request" state.
3165 }
3166 if (oops_do_has_any_strong_state(next_raw)) {
3167 // Already claimed for strong processing or requested for such.
3168 return;
3169 }
3170 if (oops_do_try_claim_weak_done_as_strong_done(next_raw)) {
3171 // Successfully claimed "weak done" as "strong done". Do the missing marking.
3172 p->do_remaining_strong_processing(this);
3173 return;
3174 }
3175 // Claim failed, some other thread got it.
3176 }
3177
3178 void nmethod::oops_do_marking_prologue() {
3179 assert_at_safepoint();
3180
3181 log_trace(gc, nmethod)("oops_do_marking_prologue");
3182 assert(_oops_do_mark_nmethods == nullptr, "must be empty");
3183 }
3184
3185 void nmethod::oops_do_marking_epilogue() {
3186 assert_at_safepoint();
3187
3188 nmethod* next = _oops_do_mark_nmethods;
3189 _oops_do_mark_nmethods = nullptr;
3190 if (next != nullptr) {
3191 nmethod* cur;
3192 do {
3193 cur = next;
3194 next = extract_nmethod(cur->_oops_do_mark_link);
3195 cur->_oops_do_mark_link = nullptr;
3196 DEBUG_ONLY(cur->verify_oop_relocations());
3197
3198 LogTarget(Trace, gc, nmethod) lt;
3199 if (lt.is_enabled()) {
3200 LogStream ls(lt);
3201 CompileTask::print(&ls, cur, "oops_do, unmark", /*short_form:*/ true);
3202 }
3203 // End if self-loop has been detected.
3204 } while (cur != next);
3205 }
3206 log_trace(gc, nmethod)("oops_do_marking_epilogue");
3207 }
3208
3209 inline bool includes(void* p, void* from, void* to) {
3210 return from <= p && p < to;
3211 }
3212
3213
3214 void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) {
3215 assert(count >= 2, "must be sentinel values, at least");
3216
3217 #ifdef ASSERT
3218 // must be sorted and unique; we do a binary search in find_pc_desc()
3219 int prev_offset = pcs[0].pc_offset();
3220 assert(prev_offset == PcDesc::lower_offset_limit,
3221 "must start with a sentinel");
3222 for (int i = 1; i < count; i++) {
3223 int this_offset = pcs[i].pc_offset();
3224 assert(this_offset > prev_offset, "offsets must be sorted");
3225 prev_offset = this_offset;
3226 }
3227 assert(prev_offset == PcDesc::upper_offset_limit,
3228 "must end with a sentinel");
3229 #endif //ASSERT
3230
3231 int size = count * sizeof(PcDesc);
3232 assert(scopes_pcs_size() >= size, "oob");
3233 memcpy(scopes_pcs_begin(), pcs, size);
3234
3235 // Adjust the final sentinel downward.
3236 PcDesc* last_pc = &scopes_pcs_begin()[count-1];
3237 assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity");
3238 last_pc->set_pc_offset(content_size() + 1);
3239 for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) {
3240 // Fill any rounding gaps with copies of the last record.
3241 last_pc[1] = last_pc[0];
3242 }
3243 // The following assert could fail if sizeof(PcDesc) is not
3244 // an integral multiple of oopSize (the rounding term).
3245 // If it fails, change the logic to always allocate a multiple
3246 // of sizeof(PcDesc), and fill unused words with copies of *last_pc.
3247 assert(last_pc + 1 == scopes_pcs_end(), "must match exactly");
3248 }
3249
3250 void nmethod::copy_scopes_data(u_char* buffer, int size) {
3251 assert(scopes_data_size() >= size, "oob");
3252 memcpy(scopes_data_begin(), buffer, size);
3253 }
3254
3255 #ifdef ASSERT
3256 static PcDesc* linear_search(int pc_offset, bool approximate, PcDesc* lower, PcDesc* upper) {
3257 PcDesc* res = nullptr;
3258 assert(lower != nullptr && lower->pc_offset() == PcDesc::lower_offset_limit,
3259 "must start with a sentinel");
3260 // lower + 1 to exclude initial sentinel
3261 for (PcDesc* p = lower + 1; p < upper; p++) {
3262 NOT_PRODUCT(--pc_nmethod_stats.pc_desc_tests); // don't count this call to match_desc
3263 if (match_desc(p, pc_offset, approximate)) {
3264 if (res == nullptr) {
3265 res = p;
3266 } else {
3267 res = (PcDesc*) badAddress;
3268 }
3269 }
3270 }
3271 return res;
3272 }
3273 #endif
3274
3275
3276 #ifndef PRODUCT
3277 // Version of method to collect statistic
3278 PcDesc* PcDescContainer::find_pc_desc(address pc, bool approximate, address code_begin,
3279 PcDesc* lower, PcDesc* upper) {
3280 ++pc_nmethod_stats.pc_desc_queries;
3281 if (approximate) ++pc_nmethod_stats.pc_desc_approx;
3282
3283 PcDesc* desc = _pc_desc_cache.last_pc_desc();
3284 assert(desc != nullptr, "PcDesc cache should be initialized already");
3285 if (desc->pc_offset() == (pc - code_begin)) {
3286 // Cached value matched
3287 ++pc_nmethod_stats.pc_desc_tests;
3288 ++pc_nmethod_stats.pc_desc_repeats;
3289 return desc;
3290 }
3291 return find_pc_desc_internal(pc, approximate, code_begin, lower, upper);
3292 }
3293 #endif
3294
3295 // Finds a PcDesc with real-pc equal to "pc"
3296 PcDesc* PcDescContainer::find_pc_desc_internal(address pc, bool approximate, address code_begin,
3297 PcDesc* lower_incl, PcDesc* upper_incl) {
3298 if ((pc < code_begin) ||
3299 (pc - code_begin) >= (ptrdiff_t) PcDesc::upper_offset_limit) {
3300 return nullptr; // PC is wildly out of range
3301 }
3302 int pc_offset = (int) (pc - code_begin);
3303
3304 // Check the PcDesc cache if it contains the desired PcDesc
3305 // (This as an almost 100% hit rate.)
3306 PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate);
3307 if (res != nullptr) {
3308 assert(res == linear_search(pc_offset, approximate, lower_incl, upper_incl), "cache ok");
3309 return res;
3310 }
3311
3312 // Fallback algorithm: quasi-linear search for the PcDesc
3313 // Find the last pc_offset less than the given offset.
3314 // The successor must be the required match, if there is a match at all.
3315 // (Use a fixed radix to avoid expensive affine pointer arithmetic.)
3316 PcDesc* lower = lower_incl; // this is initial sentinel
3317 PcDesc* upper = upper_incl - 1; // exclude final sentinel
3318 if (lower >= upper) return nullptr; // no PcDescs at all
3319
3320 #define assert_LU_OK \
3321 /* invariant on lower..upper during the following search: */ \
3322 assert(lower->pc_offset() < pc_offset, "sanity"); \
3323 assert(upper->pc_offset() >= pc_offset, "sanity")
3324 assert_LU_OK;
3325
3326 // Use the last successful return as a split point.
3327 PcDesc* mid = _pc_desc_cache.last_pc_desc();
3328 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
3329 if (mid->pc_offset() < pc_offset) {
3330 lower = mid;
3331 } else {
3332 upper = mid;
3333 }
3334
3335 // Take giant steps at first (4096, then 256, then 16, then 1)
3336 const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ DEBUG_ONLY(-1);
3337 const int RADIX = (1 << LOG2_RADIX);
3338 for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) {
3339 while ((mid = lower + step) < upper) {
3340 assert_LU_OK;
3341 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
3342 if (mid->pc_offset() < pc_offset) {
3343 lower = mid;
3344 } else {
3345 upper = mid;
3346 break;
3347 }
3348 }
3349 assert_LU_OK;
3350 }
3351
3352 // Sneak up on the value with a linear search of length ~16.
3353 while (true) {
3354 assert_LU_OK;
3355 mid = lower + 1;
3356 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
3357 if (mid->pc_offset() < pc_offset) {
3358 lower = mid;
3359 } else {
3360 upper = mid;
3361 break;
3362 }
3363 }
3364 #undef assert_LU_OK
3365
3366 if (match_desc(upper, pc_offset, approximate)) {
3367 assert(upper == linear_search(pc_offset, approximate, lower_incl, upper_incl), "search mismatch");
3368 if (!Thread::current_in_asgct()) {
3369 // we don't want to modify the cache if we're in ASGCT
3370 // which is typically called in a signal handler
3371 _pc_desc_cache.add_pc_desc(upper);
3372 }
3373 return upper;
3374 } else {
3375 assert(nullptr == linear_search(pc_offset, approximate, lower_incl, upper_incl), "search mismatch");
3376 return nullptr;
3377 }
3378 }
3379
3380 bool nmethod::check_dependency_on(DepChange& changes) {
3381 // What has happened:
3382 // 1) a new class dependee has been added
3383 // 2) dependee and all its super classes have been marked
3384 bool found_check = false; // set true if we are upset
3385 for (Dependencies::DepStream deps(this); deps.next(); ) {
3386 // Evaluate only relevant dependencies.
3387 if (deps.spot_check_dependency_at(changes) != nullptr) {
3388 found_check = true;
3389 NOT_DEBUG(break);
3390 }
3391 }
3392 return found_check;
3393 }
3394
3395 // Called from mark_for_deoptimization, when dependee is invalidated.
3396 bool nmethod::is_dependent_on_method(Method* dependee) {
3397 for (Dependencies::DepStream deps(this); deps.next(); ) {
3398 if (deps.type() != Dependencies::evol_method)
3399 continue;
3400 Method* method = deps.method_argument(0);
3401 if (method == dependee) return true;
3402 }
3403 return false;
3404 }
3405
3406 void nmethod_init() {
3407 // make sure you didn't forget to adjust the filler fields
3408 assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word");
3409 }
3410
3411 // -----------------------------------------------------------------------------
3412 // Verification
3413
3414 class VerifyOopsClosure: public OopClosure {
3415 nmethod* _nm;
3416 bool _ok;
3417 public:
3418 VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { }
3419 bool ok() { return _ok; }
3420 virtual void do_oop(oop* p) {
3421 if (oopDesc::is_oop_or_null(*p)) return;
3422 // Print diagnostic information before calling print_nmethod().
3423 // Assertions therein might prevent call from returning.
3424 tty->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)",
3425 p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm));
3426 if (_ok) {
3427 _nm->print_nmethod(true);
3428 _ok = false;
3429 }
3430 }
3431 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
3432 };
3433
3434 class VerifyMetadataClosure: public MetadataClosure {
3435 public:
3436 void do_metadata(Metadata* md) {
3437 if (md->is_method()) {
3438 Method* method = (Method*)md;
3439 assert(!method->is_old(), "Should not be installing old methods");
3440 }
3441 }
3442 };
3443
3444
3445 void nmethod::verify() {
3446 if (is_not_entrant())
3447 return;
3448
3449 // assert(oopDesc::is_oop(method()), "must be valid");
3450
3451 ResourceMark rm;
3452
3453 if (!CodeCache::contains(this)) {
3454 fatal("nmethod at " INTPTR_FORMAT " not in zone", p2i(this));
3455 }
3456
3457 if(is_native_method() )
3458 return;
3459
3460 nmethod* nm = CodeCache::find_nmethod(verified_entry_point());
3461 if (nm != this) {
3462 fatal("find_nmethod did not find this nmethod (" INTPTR_FORMAT ")", p2i(this));
3463 }
3464
3465 // Verification can triggered during shutdown after AOTCodeCache is closed.
3466 // If the Scopes data is in the AOT code cache, then we should avoid verification during shutdown.
3467 if (!is_aot() || AOTCodeCache::is_on()) {
3468 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3469 if (! p->verify(this)) {
3470 tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", p2i(this));
3471 }
3472 }
3473
3474 #ifdef ASSERT
3475 #if INCLUDE_JVMCI
3476 {
3477 // Verify that implicit exceptions that deoptimize have a PcDesc and OopMap
3478 ImmutableOopMapSet* oms = oop_maps();
3479 ImplicitExceptionTable implicit_table(this);
3480 for (uint i = 0; i < implicit_table.len(); i++) {
3481 int exec_offset = (int) implicit_table.get_exec_offset(i);
3482 if (implicit_table.get_exec_offset(i) == implicit_table.get_cont_offset(i)) {
3483 assert(pc_desc_at(code_begin() + exec_offset) != nullptr, "missing PcDesc");
3484 bool found = false;
3485 for (int i = 0, imax = oms->count(); i < imax; i++) {
3486 if (oms->pair_at(i)->pc_offset() == exec_offset) {
3487 found = true;
3488 break;
3489 }
3490 }
3491 assert(found, "missing oopmap");
3492 }
3493 }
3494 }
3495 #endif
3496 #endif
3497 }
3498
3499 VerifyOopsClosure voc(this);
3500 oops_do(&voc);
3501 assert(voc.ok(), "embedded oops must be OK");
3502 Universe::heap()->verify_nmethod(this);
3503
3504 assert(_oops_do_mark_link == nullptr, "_oops_do_mark_link for %s should be nullptr but is " PTR_FORMAT,
3505 nm->method()->external_name(), p2i(_oops_do_mark_link));
3506 if (!is_aot() || AOTCodeCache::is_on()) {
3507 verify_scopes();
3508 }
3509
3510 CompiledICLocker nm_verify(this);
3511 VerifyMetadataClosure vmc;
3512 metadata_do(&vmc);
3513 }
3514
3515
3516 void nmethod::verify_interrupt_point(address call_site, bool is_inline_cache) {
3517
3518 // Verify IC only when nmethod installation is finished.
3519 if (!is_not_installed()) {
3520 if (CompiledICLocker::is_safe(this)) {
3521 if (is_inline_cache) {
3522 CompiledIC_at(this, call_site);
3523 } else {
3524 CompiledDirectCall::at(call_site);
3525 }
3526 } else {
3527 CompiledICLocker ml_verify(this);
3528 if (is_inline_cache) {
3529 CompiledIC_at(this, call_site);
3530 } else {
3531 CompiledDirectCall::at(call_site);
3532 }
3533 }
3534 }
3535
3536 HandleMark hm(Thread::current());
3537
3538 PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address());
3539 assert(pd != nullptr, "PcDesc must exist");
3540 for (ScopeDesc* sd = new ScopeDesc(this, pd);
3541 !sd->is_top(); sd = sd->sender()) {
3542 sd->verify();
3543 }
3544 }
3545
3546 void nmethod::verify_scopes() {
3547 if( !method() ) return; // Runtime stubs have no scope
3548 if (method()->is_native()) return; // Ignore stub methods.
3549 // iterate through all interrupt point
3550 // and verify the debug information is valid.
3551 RelocIterator iter(this);
3552 while (iter.next()) {
3553 address stub = nullptr;
3554 switch (iter.type()) {
3555 case relocInfo::virtual_call_type:
3556 verify_interrupt_point(iter.addr(), true /* is_inline_cache */);
3557 break;
3558 case relocInfo::opt_virtual_call_type:
3559 stub = iter.opt_virtual_call_reloc()->static_stub();
3560 verify_interrupt_point(iter.addr(), false /* is_inline_cache */);
3561 break;
3562 case relocInfo::static_call_type:
3563 stub = iter.static_call_reloc()->static_stub();
3564 verify_interrupt_point(iter.addr(), false /* is_inline_cache */);
3565 break;
3566 case relocInfo::runtime_call_type:
3567 case relocInfo::runtime_call_w_cp_type: {
3568 address destination = iter.reloc()->value();
3569 // Right now there is no way to find out which entries support
3570 // an interrupt point. It would be nice if we had this
3571 // information in a table.
3572 break;
3573 }
3574 default:
3575 break;
3576 }
3577 assert(stub == nullptr || stub_contains(stub), "static call stub outside stub section");
3578 }
3579 }
3580
3581
3582 // -----------------------------------------------------------------------------
3583 // Printing operations
3584
3585 void nmethod::print_on_impl(outputStream* st) const {
3586 ResourceMark rm;
3587
3588 st->print("Compiled method ");
3589
3590 if (is_compiled_by_c1()) {
3591 st->print("(c1) ");
3592 } else if (is_compiled_by_c2()) {
3593 st->print("(c2) ");
3594 } else if (is_compiled_by_jvmci()) {
3595 st->print("(JVMCI) ");
3596 } else {
3597 st->print("(n/a) ");
3598 }
3599
3600 print_on_with_msg(st, nullptr);
3601
3602 if (WizardMode) {
3603 st->print("((nmethod*) " INTPTR_FORMAT ") ", p2i(this));
3604 st->print(" for method " INTPTR_FORMAT , p2i(method()));
3605 st->print(" { ");
3606 st->print_cr("%s ", state());
3607 st->print_cr("}:");
3608 }
3609 if (size () > 0) st->print_cr(" total in heap [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3610 p2i(this),
3611 p2i(this) + size(),
3612 size());
3613 if (consts_size () > 0) st->print_cr(" constants [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3614 p2i(consts_begin()),
3615 p2i(consts_end()),
3616 consts_size());
3617 if (insts_size () > 0) st->print_cr(" main code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3618 p2i(insts_begin()),
3619 p2i(insts_end()),
3620 insts_size());
3621 if (stub_size () > 0) st->print_cr(" stub code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3622 p2i(stub_begin()),
3623 p2i(stub_end()),
3624 stub_size());
3625 if (oops_size () > 0) st->print_cr(" oops [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3626 p2i(oops_begin()),
3627 p2i(oops_end()),
3628 oops_size());
3629 if (mutable_data_size() > 0) st->print_cr(" mutable data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3630 p2i(mutable_data_begin()),
3631 p2i(mutable_data_end()),
3632 mutable_data_size());
3633 if (relocation_size() > 0) st->print_cr(" relocation [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3634 p2i(relocation_begin()),
3635 p2i(relocation_end()),
3636 relocation_size());
3637 if (metadata_size () > 0) st->print_cr(" metadata [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3638 p2i(metadata_begin()),
3639 p2i(metadata_end()),
3640 metadata_size());
3641 #if INCLUDE_JVMCI
3642 if (jvmci_data_size () > 0) st->print_cr(" JVMCI data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3643 p2i(jvmci_data_begin()),
3644 p2i(jvmci_data_end()),
3645 jvmci_data_size());
3646 #endif
3647 if (immutable_data_size() > 0) st->print_cr(" immutable data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3648 p2i(immutable_data_begin()),
3649 p2i(immutable_data_end()),
3650 immutable_data_size());
3651 if (dependencies_size () > 0) st->print_cr(" dependencies [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3652 p2i(dependencies_begin()),
3653 p2i(dependencies_end()),
3654 dependencies_size());
3655 if (nul_chk_table_size() > 0) st->print_cr(" nul chk table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3656 p2i(nul_chk_table_begin()),
3657 p2i(nul_chk_table_end()),
3658 nul_chk_table_size());
3659 if (handler_table_size() > 0) st->print_cr(" handler table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3660 p2i(handler_table_begin()),
3661 p2i(handler_table_end()),
3662 handler_table_size());
3663 if (scopes_pcs_size () > 0) st->print_cr(" scopes pcs [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3664 p2i(scopes_pcs_begin()),
3665 p2i(scopes_pcs_end()),
3666 scopes_pcs_size());
3667 if (scopes_data_size () > 0) st->print_cr(" scopes data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3668 p2i(scopes_data_begin()),
3669 p2i(scopes_data_end()),
3670 scopes_data_size());
3671 #if INCLUDE_JVMCI
3672 if (speculations_size () > 0) st->print_cr(" speculations [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3673 p2i(speculations_begin()),
3674 p2i(speculations_end()),
3675 speculations_size());
3676 #endif
3677 if (AOTCodeCache::is_on() && _aot_code_entry != nullptr) {
3678 _aot_code_entry->print(st);
3679 }
3680 }
3681
3682 void nmethod::print_code() {
3683 ResourceMark m;
3684 ttyLocker ttyl;
3685 // Call the specialized decode method of this class.
3686 decode(tty);
3687 }
3688
3689 #ifndef PRODUCT // called InstanceKlass methods are available only then. Declared as PRODUCT_RETURN
3690
3691 void nmethod::print_dependencies_on(outputStream* out) {
3692 ResourceMark rm;
3693 stringStream st;
3694 st.print_cr("Dependencies:");
3695 for (Dependencies::DepStream deps(this); deps.next(); ) {
3696 deps.print_dependency(&st);
3697 InstanceKlass* ctxk = deps.context_type();
3698 if (ctxk != nullptr) {
3699 if (ctxk->is_dependent_nmethod(this)) {
3700 st.print_cr(" [nmethod<=klass]%s", ctxk->external_name());
3701 }
3702 }
3703 deps.log_dependency(); // put it into the xml log also
3704 }
3705 out->print_raw(st.as_string());
3706 }
3707 #endif
3708
3709 #if defined(SUPPORT_DATA_STRUCTS)
3710
3711 // Print the oops from the underlying CodeBlob.
3712 void nmethod::print_oops(outputStream* st) {
3713 ResourceMark m;
3714 st->print("Oops:");
3715 if (oops_begin() < oops_end()) {
3716 st->cr();
3717 for (oop* p = oops_begin(); p < oops_end(); p++) {
3718 Disassembler::print_location((unsigned char*)p, (unsigned char*)oops_begin(), (unsigned char*)oops_end(), st, true, false);
3719 st->print(PTR_FORMAT " ", *((uintptr_t*)p));
3720 if (Universe::contains_non_oop_word(p)) {
3721 st->print_cr("NON_OOP");
3722 continue; // skip non-oops
3723 }
3724 if (*p == nullptr) {
3725 st->print_cr("nullptr-oop");
3726 continue; // skip non-oops
3727 }
3728 (*p)->print_value_on(st);
3729 st->cr();
3730 }
3731 } else {
3732 st->print_cr(" <list empty>");
3733 }
3734 }
3735
3736 // Print metadata pool.
3737 void nmethod::print_metadata(outputStream* st) {
3738 ResourceMark m;
3739 st->print("Metadata:");
3740 if (metadata_begin() < metadata_end()) {
3741 st->cr();
3742 for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
3743 Disassembler::print_location((unsigned char*)p, (unsigned char*)metadata_begin(), (unsigned char*)metadata_end(), st, true, false);
3744 st->print(PTR_FORMAT " ", *((uintptr_t*)p));
3745 if (*p && *p != Universe::non_oop_word()) {
3746 (*p)->print_value_on(st);
3747 }
3748 st->cr();
3749 }
3750 } else {
3751 st->print_cr(" <list empty>");
3752 }
3753 }
3754
3755 #ifndef PRODUCT // ScopeDesc::print_on() is available only then. Declared as PRODUCT_RETURN
3756 void nmethod::print_scopes_on(outputStream* st) {
3757 // Find the first pc desc for all scopes in the code and print it.
3758 ResourceMark rm;
3759 st->print("scopes:");
3760 if (scopes_pcs_begin() < scopes_pcs_end()) {
3761 st->cr();
3762 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3763 if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null)
3764 continue;
3765
3766 ScopeDesc* sd = scope_desc_at(p->real_pc(this));
3767 while (sd != nullptr) {
3768 sd->print_on(st, p); // print output ends with a newline
3769 sd = sd->sender();
3770 }
3771 }
3772 } else {
3773 st->print_cr(" <list empty>");
3774 }
3775 }
3776 #endif
3777
3778 #ifndef PRODUCT // RelocIterator does support printing only then.
3779 void nmethod::print_relocations_on(outputStream* st) {
3780 ResourceMark m; // in case methods get printed via the debugger
3781 st->print_cr("relocations:");
3782 RelocIterator iter(this);
3783 iter.print_on(st);
3784 }
3785 #endif
3786
3787 void nmethod::print_pcs_on(outputStream* st) {
3788 ResourceMark m; // in case methods get printed via debugger
3789 st->print("pc-bytecode offsets:");
3790 if (scopes_pcs_begin() < scopes_pcs_end()) {
3791 st->cr();
3792 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3793 p->print_on(st, this); // print output ends with a newline
3794 }
3795 } else {
3796 st->print_cr(" <list empty>");
3797 }
3798 }
3799
3800 void nmethod::print_handler_table() {
3801 ExceptionHandlerTable(this).print(code_begin());
3802 }
3803
3804 void nmethod::print_nul_chk_table() {
3805 ImplicitExceptionTable(this).print(code_begin());
3806 }
3807
3808 void nmethod::print_recorded_oop(int log_n, int i) {
3809 void* value;
3810
3811 if (i == 0) {
3812 value = nullptr;
3813 } else {
3814 // Be careful around non-oop words. Don't create an oop
3815 // with that value, or it will assert in verification code.
3816 if (Universe::contains_non_oop_word(oop_addr_at(i))) {
3817 value = Universe::non_oop_word();
3818 } else {
3819 value = oop_at(i);
3820 }
3821 }
3822
3823 tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(value));
3824
3825 if (value == Universe::non_oop_word()) {
3826 tty->print("non-oop word");
3827 } else {
3828 if (value == nullptr) {
3829 tty->print("nullptr-oop");
3830 } else {
3831 oop_at(i)->print_value_on(tty);
3832 }
3833 }
3834
3835 tty->cr();
3836 }
3837
3838 void nmethod::print_recorded_oops() {
3839 const int n = oops_count();
3840 const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6;
3841 tty->print("Recorded oops:");
3842 if (n > 0) {
3843 tty->cr();
3844 for (int i = 0; i < n; i++) {
3845 print_recorded_oop(log_n, i);
3846 }
3847 } else {
3848 tty->print_cr(" <list empty>");
3849 }
3850 }
3851
3852 void nmethod::print_recorded_metadata() {
3853 const int n = metadata_count();
3854 const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6;
3855 tty->print("Recorded metadata:");
3856 if (n > 0) {
3857 tty->cr();
3858 for (int i = 0; i < n; i++) {
3859 Metadata* m = metadata_at(i);
3860 tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(m));
3861 if (m == (Metadata*)Universe::non_oop_word()) {
3862 tty->print("non-metadata word");
3863 } else if (m == nullptr) {
3864 tty->print("nullptr-oop");
3865 } else {
3866 Metadata::print_value_on_maybe_null(tty, m);
3867 }
3868 tty->cr();
3869 }
3870 } else {
3871 tty->print_cr(" <list empty>");
3872 }
3873 }
3874 #endif
3875
3876 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
3877
3878 void nmethod::print_constant_pool(outputStream* st) {
3879 //-----------------------------------
3880 //---< Print the constant pool >---
3881 //-----------------------------------
3882 int consts_size = this->consts_size();
3883 if ( consts_size > 0 ) {
3884 unsigned char* cstart = this->consts_begin();
3885 unsigned char* cp = cstart;
3886 unsigned char* cend = cp + consts_size;
3887 unsigned int bytes_per_line = 4;
3888 unsigned int CP_alignment = 8;
3889 unsigned int n;
3890
3891 st->cr();
3892
3893 //---< print CP header to make clear what's printed >---
3894 if( ((uintptr_t)cp&(CP_alignment-1)) == 0 ) {
3895 n = bytes_per_line;
3896 st->print_cr("[Constant Pool]");
3897 Disassembler::print_location(cp, cstart, cend, st, true, true);
3898 Disassembler::print_hexdata(cp, n, st, true);
3899 st->cr();
3900 } else {
3901 n = (int)((uintptr_t)cp & (bytes_per_line-1));
3902 st->print_cr("[Constant Pool (unaligned)]");
3903 }
3904
3905 //---< print CP contents, bytes_per_line at a time >---
3906 while (cp < cend) {
3907 Disassembler::print_location(cp, cstart, cend, st, true, false);
3908 Disassembler::print_hexdata(cp, n, st, false);
3909 cp += n;
3910 n = bytes_per_line;
3911 st->cr();
3912 }
3913
3914 //---< Show potential alignment gap between constant pool and code >---
3915 cend = code_begin();
3916 if( cp < cend ) {
3917 n = 4;
3918 st->print_cr("[Code entry alignment]");
3919 while (cp < cend) {
3920 Disassembler::print_location(cp, cstart, cend, st, false, false);
3921 cp += n;
3922 st->cr();
3923 }
3924 }
3925 } else {
3926 st->print_cr("[Constant Pool (empty)]");
3927 }
3928 st->cr();
3929 }
3930
3931 #endif
3932
3933 // Disassemble this nmethod.
3934 // Print additional debug information, if requested. This could be code
3935 // comments, block comments, profiling counters, etc.
3936 // The undisassembled format is useful no disassembler library is available.
3937 // The resulting hex dump (with markers) can be disassembled later, or on
3938 // another system, when/where a disassembler library is available.
3939 void nmethod::decode2(outputStream* ost) const {
3940
3941 // Called from frame::back_trace_with_decode without ResourceMark.
3942 ResourceMark rm;
3943
3944 // Make sure we have a valid stream to print on.
3945 outputStream* st = ost ? ost : tty;
3946
3947 #if defined(SUPPORT_ABSTRACT_ASSEMBLY) && ! defined(SUPPORT_ASSEMBLY)
3948 const bool use_compressed_format = true;
3949 const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() ||
3950 AbstractDisassembler::show_block_comment());
3951 #else
3952 const bool use_compressed_format = Disassembler::is_abstract();
3953 const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() ||
3954 AbstractDisassembler::show_block_comment());
3955 #endif
3956
3957 st->cr();
3958 this->print_on(st);
3959 st->cr();
3960
3961 #if defined(SUPPORT_ASSEMBLY)
3962 //----------------------------------
3963 //---< Print real disassembly >---
3964 //----------------------------------
3965 if (! use_compressed_format) {
3966 st->print_cr("[Disassembly]");
3967 Disassembler::decode(const_cast<nmethod*>(this), st);
3968 st->bol();
3969 st->print_cr("[/Disassembly]");
3970 return;
3971 }
3972 #endif
3973
3974 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
3975
3976 // Compressed undisassembled disassembly format.
3977 // The following status values are defined/supported:
3978 // = 0 - currently at bol() position, nothing printed yet on current line.
3979 // = 1 - currently at position after print_location().
3980 // > 1 - in the midst of printing instruction stream bytes.
3981 int compressed_format_idx = 0;
3982 int code_comment_column = 0;
3983 const int instr_maxlen = Assembler::instr_maxlen();
3984 const uint tabspacing = 8;
3985 unsigned char* start = this->code_begin();
3986 unsigned char* p = this->code_begin();
3987 unsigned char* end = this->code_end();
3988 unsigned char* pss = p; // start of a code section (used for offsets)
3989
3990 if ((start == nullptr) || (end == nullptr)) {
3991 st->print_cr("PrintAssembly not possible due to uninitialized section pointers");
3992 return;
3993 }
3994 #endif
3995
3996 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
3997 //---< plain abstract disassembly, no comments or anything, just section headers >---
3998 if (use_compressed_format && ! compressed_with_comments) {
3999 const_cast<nmethod*>(this)->print_constant_pool(st);
4000
4001 st->bol();
4002 st->cr();
4003 st->print_cr("Loading hsdis library failed, undisassembled code is shown in MachCode section");
4004 //---< Open the output (Marker for post-mortem disassembler) >---
4005 st->print_cr("[MachCode]");
4006 const char* header = nullptr;
4007 address p0 = p;
4008 while (p < end) {
4009 address pp = p;
4010 while ((p < end) && (header == nullptr)) {
4011 header = nmethod_section_label(p);
4012 pp = p;
4013 p += Assembler::instr_len(p);
4014 }
4015 if (pp > p0) {
4016 AbstractDisassembler::decode_range_abstract(p0, pp, start, end, st, Assembler::instr_maxlen());
4017 p0 = pp;
4018 p = pp;
4019 header = nullptr;
4020 } else if (header != nullptr) {
4021 st->bol();
4022 st->print_cr("%s", header);
4023 header = nullptr;
4024 }
4025 }
4026 //---< Close the output (Marker for post-mortem disassembler) >---
4027 st->bol();
4028 st->print_cr("[/MachCode]");
4029 return;
4030 }
4031 #endif
4032
4033 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
4034 //---< abstract disassembly with comments and section headers merged in >---
4035 if (compressed_with_comments) {
4036 const_cast<nmethod*>(this)->print_constant_pool(st);
4037
4038 st->bol();
4039 st->cr();
4040 st->print_cr("Loading hsdis library failed, undisassembled code is shown in MachCode section");
4041 //---< Open the output (Marker for post-mortem disassembler) >---
4042 st->print_cr("[MachCode]");
4043 while ((p < end) && (p != nullptr)) {
4044 const int instruction_size_in_bytes = Assembler::instr_len(p);
4045
4046 //---< Block comments for nmethod. Interrupts instruction stream, if any. >---
4047 // Outputs a bol() before and a cr() after, but only if a comment is printed.
4048 // Prints nmethod_section_label as well.
4049 if (AbstractDisassembler::show_block_comment()) {
4050 print_block_comment(st, p);
4051 if (st->position() == 0) {
4052 compressed_format_idx = 0;
4053 }
4054 }
4055
4056 //---< New location information after line break >---
4057 if (compressed_format_idx == 0) {
4058 code_comment_column = Disassembler::print_location(p, pss, end, st, false, false);
4059 compressed_format_idx = 1;
4060 }
4061
4062 //---< Code comment for current instruction. Address range [p..(p+len)) >---
4063 unsigned char* p_end = p + (ssize_t)instruction_size_in_bytes;
4064 S390_ONLY(if (p_end > end) p_end = end;) // avoid getting past the end
4065
4066 if (AbstractDisassembler::show_comment() && const_cast<nmethod*>(this)->has_code_comment(p, p_end)) {
4067 //---< interrupt instruction byte stream for code comment >---
4068 if (compressed_format_idx > 1) {
4069 st->cr(); // interrupt byte stream
4070 st->cr(); // add an empty line
4071 code_comment_column = Disassembler::print_location(p, pss, end, st, false, false);
4072 }
4073 const_cast<nmethod*>(this)->print_code_comment_on(st, code_comment_column, p, p_end );
4074 st->bol();
4075 compressed_format_idx = 0;
4076 }
4077
4078 //---< New location information after line break >---
4079 if (compressed_format_idx == 0) {
4080 code_comment_column = Disassembler::print_location(p, pss, end, st, false, false);
4081 compressed_format_idx = 1;
4082 }
4083
4084 //---< Nicely align instructions for readability >---
4085 if (compressed_format_idx > 1) {
4086 Disassembler::print_delimiter(st);
4087 }
4088
4089 //---< Now, finally, print the actual instruction bytes >---
4090 unsigned char* p0 = p;
4091 p = Disassembler::decode_instruction_abstract(p, st, instruction_size_in_bytes, instr_maxlen);
4092 compressed_format_idx += (int)(p - p0);
4093
4094 if (Disassembler::start_newline(compressed_format_idx-1)) {
4095 st->cr();
4096 compressed_format_idx = 0;
4097 }
4098 }
4099 //---< Close the output (Marker for post-mortem disassembler) >---
4100 st->bol();
4101 st->print_cr("[/MachCode]");
4102 return;
4103 }
4104 #endif
4105 }
4106
4107 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
4108
4109 const char* nmethod::reloc_string_for(u_char* begin, u_char* end) {
4110 RelocIterator iter(this, begin, end);
4111 bool have_one = false;
4112 while (iter.next()) {
4113 have_one = true;
4114 switch (iter.type()) {
4115 case relocInfo::none: {
4116 // Skip it and check next
4117 break;
4118 }
4119 case relocInfo::oop_type: {
4120 // Get a non-resizable resource-allocated stringStream.
4121 // Our callees make use of (nested) ResourceMarks.
4122 stringStream st(NEW_RESOURCE_ARRAY(char, 1024), 1024);
4123 oop_Relocation* r = iter.oop_reloc();
4124 oop obj = r->oop_value();
4125 st.print("oop(");
4126 if (obj == nullptr) st.print("nullptr");
4127 else obj->print_value_on(&st);
4128 st.print(")");
4129 return st.as_string();
4130 }
4131 case relocInfo::metadata_type: {
4132 stringStream st;
4133 metadata_Relocation* r = iter.metadata_reloc();
4134 Metadata* obj = r->metadata_value();
4135 st.print("metadata(");
4136 if (obj == nullptr) st.print("nullptr");
4137 else obj->print_value_on(&st);
4138 st.print(")");
4139 return st.as_string();
4140 }
4141 case relocInfo::runtime_call_type:
4142 case relocInfo::runtime_call_w_cp_type: {
4143 stringStream st;
4144 st.print("runtime_call");
4145 CallRelocation* r = (CallRelocation*)iter.reloc();
4146 address dest = r->destination();
4147 if (StubRoutines::contains(dest)) {
4148 StubCodeDesc* desc = StubCodeDesc::desc_for(dest);
4149 if (desc == nullptr) {
4150 desc = StubCodeDesc::desc_for(dest + frame::pc_return_offset);
4151 }
4152 if (desc != nullptr) {
4153 st.print(" Stub::%s", desc->name());
4154 return st.as_string();
4155 }
4156 }
4157 CodeBlob* cb = CodeCache::find_blob(dest);
4158 if (cb != nullptr) {
4159 st.print(" %s", cb->name());
4160 } else {
4161 ResourceMark rm;
4162 const int buflen = 1024;
4163 char* buf = NEW_RESOURCE_ARRAY(char, buflen);
4164 int offset;
4165 if (os::dll_address_to_function_name(dest, buf, buflen, &offset)) {
4166 st.print(" %s", buf);
4167 if (offset != 0) {
4168 st.print("+%d", offset);
4169 }
4170 }
4171 }
4172 return st.as_string();
4173 }
4174 case relocInfo::virtual_call_type: {
4175 stringStream st;
4176 st.print_raw("virtual_call");
4177 virtual_call_Relocation* r = iter.virtual_call_reloc();
4178 Method* m = r->method_value();
4179 if (m != nullptr) {
4180 assert(m->is_method(), "");
4181 m->print_short_name(&st);
4182 }
4183 return st.as_string();
4184 }
4185 case relocInfo::opt_virtual_call_type: {
4186 stringStream st;
4187 st.print_raw("optimized virtual_call");
4188 opt_virtual_call_Relocation* r = iter.opt_virtual_call_reloc();
4189 Method* m = r->method_value();
4190 if (m != nullptr) {
4191 assert(m->is_method(), "");
4192 m->print_short_name(&st);
4193 }
4194 return st.as_string();
4195 }
4196 case relocInfo::static_call_type: {
4197 stringStream st;
4198 st.print_raw("static_call");
4199 static_call_Relocation* r = iter.static_call_reloc();
4200 Method* m = r->method_value();
4201 if (m != nullptr) {
4202 assert(m->is_method(), "");
4203 m->print_short_name(&st);
4204 }
4205 return st.as_string();
4206 }
4207 case relocInfo::static_stub_type: return "static_stub";
4208 case relocInfo::external_word_type: return "external_word";
4209 case relocInfo::internal_word_type: return "internal_word";
4210 case relocInfo::section_word_type: return "section_word";
4211 case relocInfo::poll_type: return "poll";
4212 case relocInfo::poll_return_type: return "poll_return";
4213 case relocInfo::trampoline_stub_type: return "trampoline_stub";
4214 case relocInfo::entry_guard_type: return "entry_guard";
4215 case relocInfo::post_call_nop_type: return "post_call_nop";
4216 case relocInfo::barrier_type: {
4217 barrier_Relocation* const reloc = iter.barrier_reloc();
4218 stringStream st;
4219 st.print("barrier format=%d", reloc->format());
4220 return st.as_string();
4221 }
4222
4223 case relocInfo::type_mask: return "type_bit_mask";
4224
4225 default: {
4226 stringStream st;
4227 st.print("unknown relocInfo=%d", (int) iter.type());
4228 return st.as_string();
4229 }
4230 }
4231 }
4232 return have_one ? "other" : nullptr;
4233 }
4234
4235 // Return the last scope in (begin..end]
4236 ScopeDesc* nmethod::scope_desc_in(address begin, address end) {
4237 PcDesc* p = pc_desc_near(begin+1);
4238 if (p != nullptr && p->real_pc(this) <= end) {
4239 return new ScopeDesc(this, p);
4240 }
4241 return nullptr;
4242 }
4243
4244 const char* nmethod::nmethod_section_label(address pos) const {
4245 const char* label = nullptr;
4246 if (pos == code_begin()) label = "[Instructions begin]";
4247 if (pos == entry_point()) label = "[Entry Point]";
4248 if (pos == verified_entry_point()) label = "[Verified Entry Point]";
4249 if (pos == consts_begin() && pos != insts_begin()) label = "[Constants]";
4250 // Check stub_code before checking exception_handler or deopt_handler.
4251 if (pos == this->stub_begin()) label = "[Stub Code]";
4252 if (JVMCI_ONLY(_exception_offset >= 0 &&) pos == exception_begin()) label = "[Exception Handler]";
4253 if (JVMCI_ONLY(_deopt_handler_entry_offset != -1 &&) pos == deopt_handler_entry()) label = "[Deopt Handler Entry Point]";
4254 return label;
4255 }
4256
4257 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin, bool print_section_labels) const {
4258 if (print_section_labels) {
4259 const char* label = nmethod_section_label(block_begin);
4260 if (label != nullptr) {
4261 stream->bol();
4262 stream->print_cr("%s", label);
4263 }
4264 }
4265
4266 if (block_begin == entry_point()) {
4267 Method* m = method();
4268 if (m != nullptr) {
4269 stream->print(" # ");
4270 m->print_value_on(stream);
4271 stream->cr();
4272 }
4273 if (m != nullptr && !is_osr_method()) {
4274 ResourceMark rm;
4275 int sizeargs = m->size_of_parameters();
4276 BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs);
4277 VMRegPair* regs = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs);
4278 {
4279 int sig_index = 0;
4280 if (!m->is_static())
4281 sig_bt[sig_index++] = T_OBJECT; // 'this'
4282 for (SignatureStream ss(m->signature()); !ss.at_return_type(); ss.next()) {
4283 BasicType t = ss.type();
4284 sig_bt[sig_index++] = t;
4285 if (type2size[t] == 2) {
4286 sig_bt[sig_index++] = T_VOID;
4287 } else {
4288 assert(type2size[t] == 1, "size is 1 or 2");
4289 }
4290 }
4291 assert(sig_index == sizeargs, "");
4292 }
4293 const char* spname = "sp"; // make arch-specific?
4294 SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs);
4295 int stack_slot_offset = this->frame_size() * wordSize;
4296 int tab1 = 14, tab2 = 24;
4297 int sig_index = 0;
4298 int arg_index = (m->is_static() ? 0 : -1);
4299 bool did_old_sp = false;
4300 for (SignatureStream ss(m->signature()); !ss.at_return_type(); ) {
4301 bool at_this = (arg_index == -1);
4302 bool at_old_sp = false;
4303 BasicType t = (at_this ? T_OBJECT : ss.type());
4304 assert(t == sig_bt[sig_index], "sigs in sync");
4305 if (at_this)
4306 stream->print(" # this: ");
4307 else
4308 stream->print(" # parm%d: ", arg_index);
4309 stream->move_to(tab1);
4310 VMReg fst = regs[sig_index].first();
4311 VMReg snd = regs[sig_index].second();
4312 if (fst->is_reg()) {
4313 stream->print("%s", fst->name());
4314 if (snd->is_valid()) {
4315 stream->print(":%s", snd->name());
4316 }
4317 } else if (fst->is_stack()) {
4318 int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset;
4319 if (offset == stack_slot_offset) at_old_sp = true;
4320 stream->print("[%s+0x%x]", spname, offset);
4321 } else {
4322 stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd);
4323 }
4324 stream->print(" ");
4325 stream->move_to(tab2);
4326 stream->print("= ");
4327 if (at_this) {
4328 m->method_holder()->print_value_on(stream);
4329 } else {
4330 bool did_name = false;
4331 if (!at_this && ss.is_reference()) {
4332 Symbol* name = ss.as_symbol();
4333 name->print_value_on(stream);
4334 did_name = true;
4335 }
4336 if (!did_name)
4337 stream->print("%s", type2name(t));
4338 }
4339 if (at_old_sp) {
4340 stream->print(" (%s of caller)", spname);
4341 did_old_sp = true;
4342 }
4343 stream->cr();
4344 sig_index += type2size[t];
4345 arg_index += 1;
4346 if (!at_this) ss.next();
4347 }
4348 if (!did_old_sp) {
4349 stream->print(" # ");
4350 stream->move_to(tab1);
4351 stream->print("[%s+0x%x]", spname, stack_slot_offset);
4352 stream->print(" (%s of caller)", spname);
4353 stream->cr();
4354 }
4355 }
4356 }
4357 }
4358
4359 // Returns whether this nmethod has code comments.
4360 bool nmethod::has_code_comment(address begin, address end) {
4361 // scopes?
4362 ScopeDesc* sd = scope_desc_in(begin, end);
4363 if (sd != nullptr) return true;
4364
4365 // relocations?
4366 const char* str = reloc_string_for(begin, end);
4367 if (str != nullptr) return true;
4368
4369 // implicit exceptions?
4370 int cont_offset = ImplicitExceptionTable(this).continuation_offset((uint)(begin - code_begin()));
4371 if (cont_offset != 0) return true;
4372
4373 return false;
4374 }
4375
4376 void nmethod::print_code_comment_on(outputStream* st, int column, address begin, address end) {
4377 ImplicitExceptionTable implicit_table(this);
4378 int pc_offset = (int)(begin - code_begin());
4379 int cont_offset = implicit_table.continuation_offset(pc_offset);
4380 bool oop_map_required = false;
4381 if (cont_offset != 0) {
4382 st->move_to(column, 6, 0);
4383 if (pc_offset == cont_offset) {
4384 st->print("; implicit exception: deoptimizes");
4385 oop_map_required = true;
4386 } else {
4387 st->print("; implicit exception: dispatches to " INTPTR_FORMAT, p2i(code_begin() + cont_offset));
4388 }
4389 }
4390
4391 // Find an oopmap in (begin, end]. We use the odd half-closed
4392 // interval so that oop maps and scope descs which are tied to the
4393 // byte after a call are printed with the call itself. OopMaps
4394 // associated with implicit exceptions are printed with the implicit
4395 // instruction.
4396 address base = code_begin();
4397 ImmutableOopMapSet* oms = oop_maps();
4398 if (oms != nullptr) {
4399 for (int i = 0, imax = oms->count(); i < imax; i++) {
4400 const ImmutableOopMapPair* pair = oms->pair_at(i);
4401 const ImmutableOopMap* om = pair->get_from(oms);
4402 address pc = base + pair->pc_offset();
4403 if (pc >= begin) {
4404 #if INCLUDE_JVMCI
4405 bool is_implicit_deopt = implicit_table.continuation_offset(pair->pc_offset()) == (uint) pair->pc_offset();
4406 #else
4407 bool is_implicit_deopt = false;
4408 #endif
4409 if (is_implicit_deopt ? pc == begin : pc > begin && pc <= end) {
4410 st->move_to(column, 6, 0);
4411 st->print("; ");
4412 om->print_on(st);
4413 oop_map_required = false;
4414 }
4415 }
4416 if (pc > end) {
4417 break;
4418 }
4419 }
4420 }
4421 assert(!oop_map_required, "missed oopmap");
4422
4423 Thread* thread = Thread::current();
4424
4425 // Print any debug info present at this pc.
4426 ScopeDesc* sd = scope_desc_in(begin, end);
4427 if (sd != nullptr) {
4428 st->move_to(column, 6, 0);
4429 if (sd->bci() == SynchronizationEntryBCI) {
4430 st->print(";*synchronization entry");
4431 } else if (sd->bci() == AfterBci) {
4432 st->print(";* method exit (unlocked if synchronized)");
4433 } else if (sd->bci() == UnwindBci) {
4434 st->print(";* unwind (locked if synchronized)");
4435 } else if (sd->bci() == AfterExceptionBci) {
4436 st->print(";* unwind (unlocked if synchronized)");
4437 } else if (sd->bci() == UnknownBci) {
4438 st->print(";* unknown");
4439 } else if (sd->bci() == InvalidFrameStateBci) {
4440 st->print(";* invalid frame state");
4441 } else {
4442 if (sd->method() == nullptr) {
4443 st->print("method is nullptr");
4444 } else if (sd->method()->is_native()) {
4445 st->print("method is native");
4446 } else {
4447 Bytecodes::Code bc = sd->method()->java_code_at(sd->bci());
4448 st->print(";*%s", Bytecodes::name(bc));
4449 switch (bc) {
4450 case Bytecodes::_invokevirtual:
4451 case Bytecodes::_invokespecial:
4452 case Bytecodes::_invokestatic:
4453 case Bytecodes::_invokeinterface:
4454 {
4455 Bytecode_invoke invoke(methodHandle(thread, sd->method()), sd->bci());
4456 st->print(" ");
4457 if (invoke.name() != nullptr)
4458 invoke.name()->print_symbol_on(st);
4459 else
4460 st->print("<UNKNOWN>");
4461 break;
4462 }
4463 case Bytecodes::_getfield:
4464 case Bytecodes::_putfield:
4465 case Bytecodes::_getstatic:
4466 case Bytecodes::_putstatic:
4467 {
4468 Bytecode_field field(methodHandle(thread, sd->method()), sd->bci());
4469 st->print(" ");
4470 if (field.name() != nullptr)
4471 field.name()->print_symbol_on(st);
4472 else
4473 st->print("<UNKNOWN>");
4474 }
4475 default:
4476 break;
4477 }
4478 }
4479 st->print(" {reexecute=%d rethrow=%d return_oop=%d}", sd->should_reexecute(), sd->rethrow_exception(), sd->return_oop());
4480 }
4481
4482 // Print all scopes
4483 for (;sd != nullptr; sd = sd->sender()) {
4484 st->move_to(column, 6, 0);
4485 st->print("; -");
4486 if (sd->should_reexecute()) {
4487 st->print(" (reexecute)");
4488 }
4489 if (sd->method() == nullptr) {
4490 st->print("method is nullptr");
4491 } else {
4492 sd->method()->print_short_name(st);
4493 }
4494 int lineno = sd->method()->line_number_from_bci(sd->bci());
4495 if (lineno != -1) {
4496 st->print("@%d (line %d)", sd->bci(), lineno);
4497 } else {
4498 st->print("@%d", sd->bci());
4499 }
4500 st->cr();
4501 }
4502 }
4503
4504 // Print relocation information
4505 // Prevent memory leak: allocating without ResourceMark.
4506 ResourceMark rm;
4507 const char* str = reloc_string_for(begin, end);
4508 if (str != nullptr) {
4509 if (sd != nullptr) st->cr();
4510 st->move_to(column, 6, 0);
4511 st->print("; {%s}", str);
4512 }
4513 }
4514
4515 #endif
4516
4517 address nmethod::call_instruction_address(address pc) const {
4518 if (NativeCall::is_call_before(pc)) {
4519 NativeCall *ncall = nativeCall_before(pc);
4520 return ncall->instruction_address();
4521 }
4522 return nullptr;
4523 }
4524
4525 void nmethod::print_value_on_impl(outputStream* st) const {
4526 st->print_cr("nmethod");
4527 #if defined(SUPPORT_DATA_STRUCTS)
4528 print_on_with_msg(st, nullptr);
4529 #endif
4530 }
4531
4532 void nmethod::print_code_snippet(outputStream* st, address addr) const {
4533 if (entry_point() <= addr && addr < code_end()) {
4534 // Pointing into the nmethod's code. Try to disassemble some instructions around addr.
4535 // Determine conservative start and end points.
4536 address start;
4537 if (frame_complete_offset() != CodeOffsets::frame_never_safe &&
4538 addr >= code_begin() + frame_complete_offset()) {
4539 start = code_begin() + frame_complete_offset();
4540 } else {
4541 start = (addr < verified_entry_point()) ? entry_point() : verified_entry_point();
4542 }
4543 address start_for_hex_dump = start; // We can choose a different starting point for hex dump, below.
4544 address end = code_end();
4545
4546 // Try using relocations to find closer instruction start and end points.
4547 // (Some platforms have variable length instructions and can only
4548 // disassemble correctly at instruction start addresses.)
4549 RelocIterator iter((nmethod*)this, start);
4550 while (iter.next() && iter.addr() < addr) { // find relocation before addr
4551 // Note: There's a relocation which doesn't point to an instruction start:
4552 // ZBarrierRelocationFormatStoreGoodAfterMov with ZGC on x86_64
4553 // We could detect and skip it, but hex dump is still usable when
4554 // disassembler produces garbage in such a very rare case.
4555 start = iter.addr();
4556 // We want at least 64 Bytes ahead in hex dump.
4557 if (iter.addr() <= (addr - 64)) start_for_hex_dump = iter.addr();
4558 }
4559 if (iter.has_current()) {
4560 if (iter.addr() == addr) iter.next(); // find relocation after addr
4561 if (iter.has_current()) end = iter.addr();
4562 }
4563
4564 // Always print hex. Disassembler may still have problems when hitting an incorrect instruction start.
4565 os::print_hex_dump(st, start_for_hex_dump, end, 1, /* print_ascii=*/false);
4566 if (!Disassembler::is_abstract()) {
4567 Disassembler::decode(start, end, st);
4568 }
4569 }
4570 }
4571
4572 #ifndef PRODUCT
4573
4574 void nmethod::print_calls(outputStream* st) {
4575 RelocIterator iter(this);
4576 while (iter.next()) {
4577 switch (iter.type()) {
4578 case relocInfo::virtual_call_type: {
4579 CompiledICLocker ml_verify(this);
4580 CompiledIC_at(&iter)->print();
4581 break;
4582 }
4583 case relocInfo::static_call_type:
4584 case relocInfo::opt_virtual_call_type:
4585 st->print_cr("Direct call at " INTPTR_FORMAT, p2i(iter.reloc()->addr()));
4586 CompiledDirectCall::at(iter.reloc())->print();
4587 break;
4588 default:
4589 break;
4590 }
4591 }
4592 }
4593
4594 void nmethod::print_statistics() {
4595 ttyLocker ttyl;
4596 if (xtty != nullptr) xtty->head("statistics type='nmethod'");
4597 native_nmethod_stats.print_native_nmethod_stats();
4598 #ifdef COMPILER1
4599 c1_java_nmethod_stats.print_nmethod_stats("C1");
4600 #endif
4601 #ifdef COMPILER2
4602 c2_java_nmethod_stats.print_nmethod_stats("C2");
4603 #endif
4604 #if INCLUDE_JVMCI
4605 jvmci_java_nmethod_stats.print_nmethod_stats("JVMCI");
4606 #endif
4607 unknown_java_nmethod_stats.print_nmethod_stats("Unknown");
4608 DebugInformationRecorder::print_statistics();
4609 pc_nmethod_stats.print_pc_stats();
4610 Dependencies::print_statistics();
4611 ExternalsRecorder::print_statistics();
4612 if (xtty != nullptr) xtty->tail("statistics");
4613 }
4614
4615 #endif // !PRODUCT
4616
4617 #if INCLUDE_JVMCI
4618 void nmethod::update_speculation(JavaThread* thread) {
4619 jlong speculation = thread->pending_failed_speculation();
4620 if (speculation != 0) {
4621 guarantee(jvmci_nmethod_data() != nullptr, "failed speculation in nmethod without failed speculation list");
4622 jvmci_nmethod_data()->add_failed_speculation(this, speculation);
4623 thread->set_pending_failed_speculation(0);
4624 }
4625 }
4626
4627 const char* nmethod::jvmci_name() {
4628 if (jvmci_nmethod_data() != nullptr) {
4629 return jvmci_nmethod_data()->name();
4630 }
4631 return nullptr;
4632 }
4633
4634 bool nmethod::jvmci_skip_profile_deopt() const {
4635 return jvmci_nmethod_data() != nullptr && !jvmci_nmethod_data()->profile_deopt();
4636 }
4637 #endif
4638
4639 void nmethod::prepare_for_archiving_impl() {
4640 CodeBlob::prepare_for_archiving_impl();
4641 _deoptimization_generation = 0;
4642 _gc_epoch = 0;
4643 _method_profiling_count = 0;
4644 _osr_link = nullptr;
4645 _method = nullptr;
4646 _immutable_data = nullptr;
4647 _pc_desc_container = nullptr;
4648 _exception_cache = nullptr;
4649 _gc_data = nullptr;
4650 _oops_do_mark_link = nullptr;
4651 _compiled_ic_data = nullptr;
4652 _osr_entry_point = nullptr;
4653 _compile_id = -1;
4654 _deoptimization_status = not_marked;
4655 _is_unloading_state = 0;
4656 _state = not_installed;
4657 }