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