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