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