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 (method() != nullptr && is_native_method()) {
1034     if (method()->is_continuation_native_intrinsic()) {
1035       return "cnt";
1036     }
1037     return "c2n";
1038   }
1039   return nullptr;
1040 }
1041 
1042 const char* nmethod::compiler_name() const {
1043   return compilertype2name(_compiler_type);
1044 }
1045 
1046 #ifdef ASSERT
1047 class CheckForOopsClosure : public OopClosure {
1048   bool _found_oop = false;
1049  public:
1050   virtual void do_oop(oop* o) { _found_oop = true; }
1051   virtual void do_oop(narrowOop* o) { _found_oop = true; }
1052   bool found_oop() { return _found_oop; }
1053 };
1054 class CheckForMetadataClosure : public MetadataClosure {
1055   bool _found_metadata = false;
1056   Metadata* _ignore = nullptr;
1057  public:
1058   CheckForMetadataClosure(Metadata* ignore) : _ignore(ignore) {}
1059   virtual void do_metadata(Metadata* md) { if (md != _ignore) _found_metadata = true; }
1060   bool found_metadata() { return _found_metadata; }
1061 };
1062 
1063 static void assert_no_oops_or_metadata(nmethod* nm) {
1064   if (nm == nullptr) return;
1065   assert(nm->oop_maps() == nullptr, "expectation");
1066 
1067   CheckForOopsClosure cfo;
1068   nm->oops_do(&cfo);
1069   assert(!cfo.found_oop(), "no oops allowed");
1070 
1071   // We allow an exception for the own Method, but require its class to be permanent.
1072   Method* own_method = nm->method();
1073   CheckForMetadataClosure cfm(/* ignore reference to own Method */ own_method);
1074   nm->metadata_do(&cfm);
1075   assert(!cfm.found_metadata(), "no metadata allowed");
1076 
1077   assert(own_method->method_holder()->class_loader_data()->is_permanent_class_loader_data(),
1078          "Method's class needs to be permanent");
1079 }
1080 #endif
1081 
1082 static int required_mutable_data_size(CodeBuffer* code_buffer,
1083                                       int jvmci_data_size = 0) {
1084   return align_up(code_buffer->total_relocation_size(), oopSize) +
1085          align_up(code_buffer->total_metadata_size(), oopSize) +
1086          align_up(jvmci_data_size, oopSize);
1087 }
1088 
1089 nmethod* nmethod::new_native_nmethod(const methodHandle& method,
1090   int compile_id,
1091   CodeBuffer *code_buffer,
1092   int vep_offset,
1093   int frame_complete,
1094   int frame_size,
1095   ByteSize basic_lock_owner_sp_offset,
1096   ByteSize basic_lock_sp_offset,
1097   OopMapSet* oop_maps,
1098   int exception_handler) {
1099   code_buffer->finalize_oop_references(method);
1100   // create nmethod
1101   nmethod* nm = nullptr;
1102   int native_nmethod_size = CodeBlob::allocation_size(code_buffer, sizeof(nmethod));
1103   {
1104     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1105 
1106     CodeOffsets offsets;
1107     offsets.set_value(CodeOffsets::Verified_Entry, vep_offset);
1108     offsets.set_value(CodeOffsets::Frame_Complete, frame_complete);
1109     if (exception_handler != -1) {
1110       offsets.set_value(CodeOffsets::Exceptions, exception_handler);
1111     }
1112 
1113     int mutable_data_size = required_mutable_data_size(code_buffer);
1114 
1115     // MH intrinsics are dispatch stubs which are compatible with NonNMethod space.
1116     // IsUnloadingBehaviour::is_unloading needs to handle them separately.
1117     bool allow_NonNMethod_space = method->can_be_allocated_in_NonNMethod_space();
1118     nm = new (native_nmethod_size, allow_NonNMethod_space)
1119     nmethod(method(), compiler_none, native_nmethod_size,
1120             compile_id, &offsets,
1121             code_buffer, frame_size,
1122             basic_lock_owner_sp_offset,
1123             basic_lock_sp_offset,
1124             oop_maps, mutable_data_size);
1125     DEBUG_ONLY( if (allow_NonNMethod_space) assert_no_oops_or_metadata(nm); )
1126     NOT_PRODUCT(if (nm != nullptr) native_nmethod_stats.note_native_nmethod(nm));
1127   }
1128 
1129   if (nm != nullptr) {
1130     // verify nmethod
1131     DEBUG_ONLY(nm->verify();) // might block
1132 
1133     nm->log_new_nmethod();
1134   }
1135   return nm;
1136 }
1137 
1138 void nmethod::record_nmethod_dependency() {
1139   // To make dependency checking during class loading fast, record
1140   // the nmethod dependencies in the classes it is dependent on.
1141   // This allows the dependency checking code to simply walk the
1142   // class hierarchy above the loaded class, checking only nmethods
1143   // which are dependent on those classes.  The slow way is to
1144   // check every nmethod for dependencies which makes it linear in
1145   // the number of methods compiled.  For applications with a lot
1146   // classes the slow way is too slow.
1147   for (Dependencies::DepStream deps(this); deps.next(); ) {
1148     if (deps.type() == Dependencies::call_site_target_value) {
1149       // CallSite dependencies are managed on per-CallSite instance basis.
1150       oop call_site = deps.argument_oop(0);
1151       MethodHandles::add_dependent_nmethod(call_site, this);
1152     } else {
1153       InstanceKlass* ik = deps.context_type();
1154       if (ik == nullptr) {
1155         continue;  // ignore things like evol_method
1156       }
1157       // record this nmethod as dependent on this klass
1158       ik->add_dependent_nmethod(this);
1159     }
1160   }
1161 }
1162 
1163 nmethod* nmethod::new_nmethod(const methodHandle& method,
1164   int compile_id,
1165   int entry_bci,
1166   CodeOffsets* offsets,
1167   int orig_pc_offset,
1168   DebugInformationRecorder* debug_info,
1169   Dependencies* dependencies,
1170   CodeBuffer* code_buffer, int frame_size,
1171   OopMapSet* oop_maps,
1172   ExceptionHandlerTable* handler_table,
1173   ImplicitExceptionTable* nul_chk_table,
1174   AbstractCompiler* compiler,
1175   CompLevel comp_level
1176   , AOTCodeEntry* aot_code_entry
1177 #if INCLUDE_JVMCI
1178   , char* speculations,
1179   int speculations_len,
1180   JVMCINMethodData* jvmci_data
1181 #endif
1182 )
1183 {
1184   assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");
1185   code_buffer->finalize_oop_references(method);
1186   // create nmethod
1187   nmethod* nm = nullptr;
1188   int nmethod_size = CodeBlob::allocation_size(code_buffer, sizeof(nmethod));
1189 
1190   int immutable_data_size =
1191       adjust_pcs_size(debug_info->pcs_size())
1192     + align_up((int)dependencies->size_in_bytes(), oopSize)
1193     + align_up(handler_table->size_in_bytes()    , oopSize)
1194     + align_up(nul_chk_table->size_in_bytes()    , oopSize)
1195 #if INCLUDE_JVMCI
1196     + align_up(speculations_len                  , oopSize)
1197 #endif
1198     + align_up(debug_info->data_size()           , oopSize);
1199 
1200   // First, allocate space for immutable data in C heap.
1201   address immutable_data = nullptr;
1202   if (immutable_data_size > 0) {
1203     immutable_data = (address)os::malloc(immutable_data_size, mtCode);
1204     if (immutable_data == nullptr) {
1205       vm_exit_out_of_memory(immutable_data_size, OOM_MALLOC_ERROR, "nmethod: no space for immutable data");
1206       return nullptr;
1207     }
1208   }
1209 
1210   int mutable_data_size = required_mutable_data_size(code_buffer
1211     JVMCI_ONLY(COMMA (compiler->is_jvmci() ? jvmci_data->size() : 0)));
1212 
1213   {
1214     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1215 
1216     nm = new (nmethod_size, comp_level)
1217     nmethod(method(), compiler->type(), nmethod_size, immutable_data_size, mutable_data_size,
1218             compile_id, entry_bci, immutable_data, offsets, orig_pc_offset,
1219             debug_info, dependencies, code_buffer, frame_size, oop_maps,
1220             handler_table, nul_chk_table, compiler, comp_level, aot_code_entry
1221 #if INCLUDE_JVMCI
1222             , speculations,
1223             speculations_len,
1224             jvmci_data
1225 #endif
1226             );
1227 
1228     if (nm != nullptr) {
1229       nm->record_nmethod_dependency();
1230       NOT_PRODUCT(note_java_nmethod(nm));
1231     }
1232   }
1233   // Do verification and logging outside CodeCache_lock.
1234   if (nm != nullptr) {
1235 
1236 #ifdef ASSERT
1237     LogTarget(Debug, aot, codecache, nmethod) log;
1238     if (log.is_enabled()) {
1239       LogStream out(log);
1240       out.print_cr("== new_nmethod 2");
1241       FlagSetting fs(PrintRelocations, true);
1242       nm->print_on_impl(&out);
1243       nm->decode(&out);
1244     }
1245 #endif
1246 
1247     // Safepoints in nmethod::verify aren't allowed because nm hasn't been installed yet.
1248     DEBUG_ONLY(nm->verify();)
1249     nm->log_new_nmethod();
1250   }
1251   return nm;
1252 }
1253 
1254 void nmethod::restore_from_archive(nmethod* archived_nm,
1255                                    const methodHandle& method,
1256                                    int compile_id,
1257                                    address reloc_data,
1258                                    GrowableArray<Handle>& oop_list,
1259                                    GrowableArray<Metadata*>& metadata_list,
1260                                    ImmutableOopMapSet* oop_maps,
1261                                    address immutable_data,
1262                                    GrowableArray<Handle>& reloc_imm_oop_list,
1263                                    GrowableArray<Metadata*>& reloc_imm_metadata_list,
1264 #ifndef PRODUCT
1265                                    AsmRemarks& archived_asm_remarks,
1266                                    DbgStrings& archived_dbg_strings,
1267 #endif /* PRODUCT */
1268                                    AOTCodeReader* aot_code_reader)
1269 {
1270   archived_nm->copy_to((address)this);
1271   set_name("nmethod");
1272   set_method(method());
1273 
1274   _compile_id = compile_id;
1275   // allocate _mutable_data before copying relocation data because relocation data is now stored as part of mutable data area
1276   if (archived_nm->mutable_data_size() > 0) {
1277     _mutable_data = (address)os::malloc(archived_nm->mutable_data_size(), mtCode);
1278     if (_mutable_data == nullptr) {
1279       vm_exit_out_of_memory(archived_nm->mutable_data_size(), OOM_MALLOC_ERROR, "codebuffer: no space for mutable data");
1280     }
1281   }
1282   memcpy((address)relocation_begin(), reloc_data, archived_nm->relocation_size());
1283   set_oop_maps(oop_maps);
1284   set_immutable_data(immutable_data);
1285   copy_values(&oop_list);
1286   copy_values(&metadata_list);
1287 
1288   aot_code_reader->apply_relocations(this, reloc_imm_oop_list, reloc_imm_metadata_list);
1289 
1290 #ifndef PRODUCT
1291   AsmRemarks::init(asm_remarks());
1292   use_remarks(archived_asm_remarks);
1293   archived_asm_remarks.clear();
1294   DbgStrings::init(dbg_strings());
1295   use_strings(archived_dbg_strings);
1296   archived_dbg_strings.clear();
1297 #endif /* PRODUCT */
1298 
1299   // Flush the code block
1300   ICache::invalidate_range(code_begin(), code_size());
1301 
1302   // Create cache after PcDesc data is copied - it will be used to initialize cache
1303   _pc_desc_container = new PcDescContainer(scopes_pcs_begin());
1304 
1305   set_aot_code_entry(aot_code_reader->aot_code_entry());
1306 
1307   post_init();
1308 }
1309 
1310 nmethod* nmethod::new_nmethod(nmethod* archived_nm,
1311                               const methodHandle& method,
1312                               AbstractCompiler* compiler,
1313                               int compile_id,
1314                               address reloc_data,
1315                               GrowableArray<Handle>& oop_list,
1316                               GrowableArray<Metadata*>& metadata_list,
1317                               ImmutableOopMapSet* oop_maps,
1318                               address immutable_data,
1319                               GrowableArray<Handle>& reloc_imm_oop_list,
1320                               GrowableArray<Metadata*>& reloc_imm_metadata_list,
1321 #ifndef PRODUCT
1322                               AsmRemarks& asm_remarks,
1323                               DbgStrings& dbg_strings,
1324 #endif /* PRODUCT */
1325                               AOTCodeReader* aot_code_reader)
1326 {
1327   nmethod* nm = nullptr;
1328   int nmethod_size = archived_nm->size();
1329   // create nmethod
1330   {
1331     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1332     nm = (nmethod *)CodeCache::allocate(nmethod_size, CodeCache::get_code_blob_type(archived_nm->comp_level()));
1333     if (nm != nullptr) {
1334       nm->restore_from_archive(archived_nm,
1335                                method,
1336                                compile_id,
1337                                reloc_data,
1338                                oop_list,
1339                                metadata_list,
1340                                oop_maps,
1341                                immutable_data,
1342                                reloc_imm_oop_list,
1343                                reloc_imm_metadata_list,
1344                                NOT_PRODUCT_ARG(asm_remarks)
1345                                NOT_PRODUCT_ARG(dbg_strings)
1346                                aot_code_reader);
1347       nm->record_nmethod_dependency();
1348       NOT_PRODUCT(note_java_nmethod(nm));
1349     }
1350   }
1351   // Do verification and logging outside CodeCache_lock.
1352   if (nm != nullptr) {
1353 #ifdef ASSERT
1354     LogTarget(Debug, aot, codecache, nmethod) log;
1355     if (log.is_enabled()) {
1356       LogStream out(log);
1357       out.print_cr("== new_nmethod 2");
1358       FlagSetting fs(PrintRelocations, true);
1359       nm->print_on_impl(&out);
1360       nm->decode(&out);
1361     }
1362 #endif
1363     // Safepoints in nmethod::verify aren't allowed because nm hasn't been installed yet.
1364     DEBUG_ONLY(nm->verify();)
1365     nm->log_new_nmethod();
1366   }
1367   return nm;
1368 }
1369 
1370 // Fill in default values for various fields
1371 void nmethod::init_defaults(CodeBuffer *code_buffer, CodeOffsets* offsets) {
1372   // avoid uninitialized fields, even for short time periods
1373   _exception_cache            = nullptr;
1374   _gc_data                    = nullptr;
1375   _oops_do_mark_link          = nullptr;
1376   _compiled_ic_data           = nullptr;
1377 
1378   _is_unloading_state         = 0;
1379   _state                      = not_installed;
1380 
1381   _has_unsafe_access          = 0;
1382   _has_method_handle_invokes  = 0;
1383   _has_wide_vectors           = 0;
1384   _has_monitors               = 0;
1385   _has_scoped_access          = 0;
1386   _has_flushed_dependencies   = 0;
1387   _is_unlinked                = 0;
1388   _load_reported              = 0; // jvmti state
1389   _preloaded                  = 0;
1390   _has_clinit_barriers        = 0;
1391 
1392   _used                       = false;
1393   _deoptimization_status      = not_marked;
1394 
1395   // SECT_CONSTS is first in code buffer so the offset should be 0.
1396   int consts_offset = code_buffer->total_offset_of(code_buffer->consts());
1397   assert(consts_offset == 0, "const_offset: %d", consts_offset);
1398 
1399   _stub_offset = content_offset() + code_buffer->total_offset_of(code_buffer->stubs());
1400 
1401   CHECKED_CAST(_entry_offset,              uint16_t, (offsets->value(CodeOffsets::Entry)));
1402   CHECKED_CAST(_verified_entry_offset,     uint16_t, (offsets->value(CodeOffsets::Verified_Entry)));
1403 
1404   _skipped_instructions_size = code_buffer->total_skipped_instructions_size();
1405 }
1406 
1407 // Post initialization
1408 void nmethod::post_init() {
1409   clear_unloading_state();
1410 
1411   finalize_relocations();
1412 
1413   Universe::heap()->register_nmethod(this);
1414   DEBUG_ONLY(Universe::heap()->verify_nmethod(this));
1415 
1416   CodeCache::commit(this);
1417 }
1418 
1419 // For native wrappers
1420 nmethod::nmethod(
1421   Method* method,
1422   CompilerType type,
1423   int nmethod_size,
1424   int compile_id,
1425   CodeOffsets* offsets,
1426   CodeBuffer* code_buffer,
1427   int frame_size,
1428   ByteSize basic_lock_owner_sp_offset,
1429   ByteSize basic_lock_sp_offset,
1430   OopMapSet* oop_maps,
1431   int mutable_data_size)
1432   : CodeBlob("native nmethod", CodeBlobKind::Nmethod, code_buffer, nmethod_size, sizeof(nmethod),
1433              offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps, false, mutable_data_size),
1434   _deoptimization_generation(0),
1435   _gc_epoch(CodeCache::gc_epoch()),
1436   _method(method),
1437   _native_receiver_sp_offset(basic_lock_owner_sp_offset),
1438   _native_basic_lock_sp_offset(basic_lock_sp_offset)
1439 {
1440   {
1441     DEBUG_ONLY(NoSafepointVerifier nsv;)
1442     assert_locked_or_safepoint(CodeCache_lock);
1443 
1444     init_defaults(code_buffer, offsets);
1445 
1446     _osr_entry_point         = nullptr;
1447     _pc_desc_container       = nullptr;
1448     _entry_bci               = InvocationEntryBci;
1449     _compile_id              = compile_id;
1450     _comp_level              = CompLevel_none;
1451     _compiler_type           = type;
1452     _orig_pc_offset          = 0;
1453     _num_stack_arg_slots     = 0;
1454 
1455     if (offsets->value(CodeOffsets::Exceptions) != -1) {
1456       // Continuation enter intrinsic
1457       _exception_offset      = code_offset() + offsets->value(CodeOffsets::Exceptions);
1458     } else {
1459       _exception_offset      = 0;
1460     }
1461     // Native wrappers do not have deopt handlers. Make the values
1462     // something that will never match a pc like the nmethod vtable entry
1463     _deopt_handler_offset    = 0;
1464     _deopt_mh_handler_offset = 0;
1465     _aot_code_entry          = nullptr;
1466     _method_profiling_count  = 0;
1467     _unwind_handler_offset   = 0;
1468 
1469     CHECKED_CAST(_oops_size, uint16_t, align_up(code_buffer->total_oop_size(), oopSize));
1470     uint16_t metadata_size;
1471     CHECKED_CAST(metadata_size, uint16_t, align_up(code_buffer->total_metadata_size(), wordSize));
1472     JVMCI_ONLY( _metadata_size = metadata_size; )
1473     assert(_mutable_data_size == _relocation_size + metadata_size,
1474            "wrong mutable data size: %d != %d + %d",
1475            _mutable_data_size, _relocation_size, metadata_size);
1476 
1477     // native wrapper does not have read-only data but we need unique not null address
1478     _immutable_data          = blob_end();
1479     _immutable_data_size     = 0;
1480     _nul_chk_table_offset    = 0;
1481     _handler_table_offset    = 0;
1482     _scopes_pcs_offset       = 0;
1483     _scopes_data_offset      = 0;
1484 #if INCLUDE_JVMCI
1485     _speculations_offset     = 0;
1486 #endif
1487 
1488     code_buffer->copy_code_and_locs_to(this);
1489     code_buffer->copy_values_to(this);
1490 
1491     post_init();
1492   }
1493 
1494   if (PrintNativeNMethods || PrintDebugInfo || PrintRelocations || PrintDependencies) {
1495     ttyLocker ttyl;  // keep the following output all in one block
1496     // This output goes directly to the tty, not the compiler log.
1497     // To enable tools to match it up with the compilation activity,
1498     // be sure to tag this tty output with the compile ID.
1499     if (xtty != nullptr) {
1500       xtty->begin_head("print_native_nmethod");
1501       xtty->method(_method);
1502       xtty->stamp();
1503       xtty->end_head(" address='" INTPTR_FORMAT "'", (intptr_t) this);
1504     }
1505     // Print the header part, then print the requested information.
1506     // This is both handled in decode2(), called via print_code() -> decode()
1507     if (PrintNativeNMethods) {
1508       tty->print_cr("-------------------------- Assembly (native nmethod) ---------------------------");
1509       print_code();
1510       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1511 #if defined(SUPPORT_DATA_STRUCTS)
1512       if (AbstractDisassembler::show_structs()) {
1513         if (oop_maps != nullptr) {
1514           tty->print("oop maps:"); // oop_maps->print_on(tty) outputs a cr() at the beginning
1515           oop_maps->print_on(tty);
1516           tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1517         }
1518       }
1519 #endif
1520     } else {
1521       print(); // print the header part only.
1522     }
1523 #if defined(SUPPORT_DATA_STRUCTS)
1524     if (AbstractDisassembler::show_structs()) {
1525       if (PrintRelocations) {
1526         print_relocations_on(tty);
1527         tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1528       }
1529     }
1530 #endif
1531     if (xtty != nullptr) {
1532       xtty->tail("print_native_nmethod");
1533     }
1534   }
1535 }
1536 
1537 void* nmethod::operator new(size_t size, int nmethod_size, int comp_level) throw () {
1538   return CodeCache::allocate(nmethod_size, CodeCache::get_code_blob_type(comp_level));
1539 }
1540 
1541 void* nmethod::operator new(size_t size, int nmethod_size, bool allow_NonNMethod_space) throw () {
1542   // Try MethodNonProfiled and MethodProfiled.
1543   void* return_value = CodeCache::allocate(nmethod_size, CodeBlobType::MethodNonProfiled);
1544   if (return_value != nullptr || !allow_NonNMethod_space) return return_value;
1545   // Try NonNMethod or give up.
1546   return CodeCache::allocate(nmethod_size, CodeBlobType::NonNMethod);
1547 }
1548 
1549 // For normal JIT compiled code
1550 nmethod::nmethod(
1551   Method* method,
1552   CompilerType type,
1553   int nmethod_size,
1554   int immutable_data_size,
1555   int mutable_data_size,
1556   int compile_id,
1557   int entry_bci,
1558   address immutable_data,
1559   CodeOffsets* offsets,
1560   int orig_pc_offset,
1561   DebugInformationRecorder* debug_info,
1562   Dependencies* dependencies,
1563   CodeBuffer *code_buffer,
1564   int frame_size,
1565   OopMapSet* oop_maps,
1566   ExceptionHandlerTable* handler_table,
1567   ImplicitExceptionTable* nul_chk_table,
1568   AbstractCompiler* compiler,
1569   CompLevel comp_level
1570   , AOTCodeEntry* aot_code_entry
1571 #if INCLUDE_JVMCI
1572   , char* speculations,
1573   int speculations_len,
1574   JVMCINMethodData* jvmci_data
1575 #endif
1576   )
1577   : CodeBlob("nmethod", CodeBlobKind::Nmethod, code_buffer, nmethod_size, sizeof(nmethod),
1578              offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps, false, mutable_data_size),
1579   _deoptimization_generation(0),
1580   _gc_epoch(CodeCache::gc_epoch()),
1581   _method(method),
1582   _osr_link(nullptr)
1583 {
1584   assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");
1585   {
1586     DEBUG_ONLY(NoSafepointVerifier nsv;)
1587     assert_locked_or_safepoint(CodeCache_lock);
1588 
1589     init_defaults(code_buffer, offsets);
1590     _aot_code_entry          = aot_code_entry;
1591     _method_profiling_count  = 0;
1592 
1593     _osr_entry_point = code_begin() + offsets->value(CodeOffsets::OSR_Entry);
1594     _entry_bci       = entry_bci;
1595     _compile_id      = compile_id;
1596     _comp_level      = comp_level;
1597     _compiler_type   = type;
1598     _orig_pc_offset  = orig_pc_offset;
1599 
1600     _num_stack_arg_slots = entry_bci != InvocationEntryBci ? 0 : _method->constMethod()->num_stack_arg_slots();
1601 
1602     set_ctable_begin(header_begin() + content_offset());
1603 
1604 #if INCLUDE_JVMCI
1605     if (compiler->is_jvmci()) {
1606       // JVMCI might not produce any stub sections
1607       if (offsets->value(CodeOffsets::Exceptions) != -1) {
1608         _exception_offset        = code_offset() + offsets->value(CodeOffsets::Exceptions);
1609       } else {
1610         _exception_offset        = -1;
1611       }
1612       if (offsets->value(CodeOffsets::Deopt) != -1) {
1613         _deopt_handler_offset    = code_offset() + offsets->value(CodeOffsets::Deopt);
1614       } else {
1615         _deopt_handler_offset    = -1;
1616       }
1617       if (offsets->value(CodeOffsets::DeoptMH) != -1) {
1618         _deopt_mh_handler_offset = code_offset() + offsets->value(CodeOffsets::DeoptMH);
1619       } else {
1620         _deopt_mh_handler_offset = -1;
1621       }
1622     } else
1623 #endif
1624     {
1625       // Exception handler and deopt handler are in the stub section
1626       assert(offsets->value(CodeOffsets::Exceptions) != -1, "must be set");
1627       assert(offsets->value(CodeOffsets::Deopt     ) != -1, "must be set");
1628 
1629       _exception_offset          = _stub_offset + offsets->value(CodeOffsets::Exceptions);
1630       _deopt_handler_offset      = _stub_offset + offsets->value(CodeOffsets::Deopt);
1631       if (offsets->value(CodeOffsets::DeoptMH) != -1) {
1632         _deopt_mh_handler_offset = _stub_offset + offsets->value(CodeOffsets::DeoptMH);
1633       } else {
1634         _deopt_mh_handler_offset = -1;
1635       }
1636     }
1637     if (offsets->value(CodeOffsets::UnwindHandler) != -1) {
1638       // C1 generates UnwindHandler at the end of instructions section.
1639       // Calculate positive offset as distance between the start of stubs section
1640       // (which is also the end of instructions section) and the start of the handler.
1641       int unwind_handler_offset = code_offset() + offsets->value(CodeOffsets::UnwindHandler);
1642       CHECKED_CAST(_unwind_handler_offset, int16_t, (_stub_offset - unwind_handler_offset));
1643     } else {
1644       _unwind_handler_offset = -1;
1645     }
1646 
1647     CHECKED_CAST(_oops_size, uint16_t, align_up(code_buffer->total_oop_size(), oopSize));
1648     uint16_t metadata_size;
1649     CHECKED_CAST(metadata_size, uint16_t, align_up(code_buffer->total_metadata_size(), wordSize));
1650     JVMCI_ONLY( _metadata_size = metadata_size; )
1651     int jvmci_data_size = 0 JVMCI_ONLY( + align_up(compiler->is_jvmci() ? jvmci_data->size() : 0, oopSize));
1652     assert(_mutable_data_size == _relocation_size + metadata_size + jvmci_data_size,
1653            "wrong mutable data size: %d != %d + %d + %d",
1654            _mutable_data_size, _relocation_size, metadata_size, jvmci_data_size);
1655     assert(nmethod_size == data_end() - header_begin(), "wrong nmethod size: %d != %d",
1656            nmethod_size, (int)(code_end() - header_begin()));
1657 
1658     _immutable_data_size  = immutable_data_size;
1659     if (immutable_data_size > 0) {
1660       assert(immutable_data != nullptr, "required");
1661       _immutable_data     = immutable_data;
1662     } else {
1663       // We need unique not null address
1664       _immutable_data     = blob_end();
1665     }
1666     CHECKED_CAST(_nul_chk_table_offset, uint16_t, (align_up((int)dependencies->size_in_bytes(), oopSize)));
1667     CHECKED_CAST(_handler_table_offset, uint16_t, (_nul_chk_table_offset + align_up(nul_chk_table->size_in_bytes(), oopSize)));
1668     _scopes_pcs_offset    = _handler_table_offset + align_up(handler_table->size_in_bytes(), oopSize);
1669     _scopes_data_offset   = _scopes_pcs_offset    + adjust_pcs_size(debug_info->pcs_size());
1670 
1671 #if INCLUDE_JVMCI
1672     _speculations_offset  = _scopes_data_offset   + align_up(debug_info->data_size(), oopSize);
1673     DEBUG_ONLY( int immutable_data_end_offset = _speculations_offset  + align_up(speculations_len, oopSize); )
1674 #else
1675     DEBUG_ONLY( int immutable_data_end_offset = _scopes_data_offset + align_up(debug_info->data_size(), oopSize); )
1676 #endif
1677     assert(immutable_data_end_offset <= immutable_data_size, "wrong read-only data size: %d > %d",
1678            immutable_data_end_offset, immutable_data_size);
1679 
1680     // Copy code and relocation info
1681     code_buffer->copy_code_and_locs_to(this);
1682     // Copy oops and metadata
1683     code_buffer->copy_values_to(this);
1684     dependencies->copy_to(this);
1685     // Copy PcDesc and ScopeDesc data
1686     debug_info->copy_to(this);
1687 
1688     // Create cache after PcDesc data is copied - it will be used to initialize cache
1689     _pc_desc_container = new PcDescContainer(scopes_pcs_begin());
1690 
1691 #if INCLUDE_JVMCI
1692     if (compiler->is_jvmci()) {
1693       // Initialize the JVMCINMethodData object inlined into nm
1694       jvmci_nmethod_data()->copy(jvmci_data);
1695     }
1696 #endif
1697 
1698     // Copy contents of ExceptionHandlerTable to nmethod
1699     handler_table->copy_to(this);
1700     nul_chk_table->copy_to(this);
1701 
1702 #if INCLUDE_JVMCI
1703     // Copy speculations to nmethod
1704     if (speculations_size() != 0) {
1705       memcpy(speculations_begin(), speculations, speculations_len);
1706     }
1707 #endif
1708 
1709     post_init();
1710 
1711     // we use the information of entry points to find out if a method is
1712     // static or non static
1713     assert(compiler->is_c2() || compiler->is_jvmci() ||
1714            _method->is_static() == (entry_point() == verified_entry_point()),
1715            " entry points must be same for static methods and vice versa");
1716   }
1717 }
1718 
1719 // Print a short set of xml attributes to identify this nmethod.  The
1720 // output should be embedded in some other element.
1721 void nmethod::log_identity(xmlStream* log) const {
1722   assert(log->inside_attrs_or_error(), "printing attributes");
1723   log->print(" code_compile_id='%d'", compile_id());
1724   const char* nm_kind = compile_kind();
1725   if (nm_kind != nullptr)  log->print(" code_compile_kind='%s'", nm_kind);
1726   log->print(" code_compiler='%s'", compiler_name());
1727   if (TieredCompilation) {
1728     log->print(" code_compile_level='%d'", comp_level());
1729   }
1730 #if INCLUDE_JVMCI
1731   if (jvmci_nmethod_data() != nullptr) {
1732     const char* jvmci_name = jvmci_nmethod_data()->name();
1733     if (jvmci_name != nullptr) {
1734       log->print(" jvmci_mirror_name='");
1735       log->text("%s", jvmci_name);
1736       log->print("'");
1737     }
1738   }
1739 #endif
1740 }
1741 
1742 
1743 #define LOG_OFFSET(log, name)                    \
1744   if (p2i(name##_end()) - p2i(name##_begin())) \
1745     log->print(" " XSTR(name) "_offset='%zd'"    , \
1746                p2i(name##_begin()) - p2i(this))
1747 
1748 
1749 void nmethod::log_new_nmethod() const {
1750   if (LogCompilation && xtty != nullptr) {
1751     ttyLocker ttyl;
1752     xtty->begin_elem("nmethod");
1753     log_identity(xtty);
1754     xtty->print(" entry='" INTPTR_FORMAT "' size='%d'", p2i(code_begin()), size());
1755     xtty->print(" address='" INTPTR_FORMAT "'", p2i(this));
1756 
1757     LOG_OFFSET(xtty, relocation);
1758     LOG_OFFSET(xtty, consts);
1759     LOG_OFFSET(xtty, insts);
1760     LOG_OFFSET(xtty, stub);
1761     LOG_OFFSET(xtty, scopes_data);
1762     LOG_OFFSET(xtty, scopes_pcs);
1763     LOG_OFFSET(xtty, dependencies);
1764     LOG_OFFSET(xtty, handler_table);
1765     LOG_OFFSET(xtty, nul_chk_table);
1766     LOG_OFFSET(xtty, oops);
1767     LOG_OFFSET(xtty, metadata);
1768 
1769     xtty->method(method());
1770     xtty->stamp();
1771     xtty->end_elem();
1772   }
1773 }
1774 
1775 #undef LOG_OFFSET
1776 
1777 
1778 // Print out more verbose output usually for a newly created nmethod.
1779 void nmethod::print_on_with_msg(outputStream* st, const char* msg) const {
1780   if (st != nullptr) {
1781     ttyLocker ttyl;
1782     if (WizardMode) {
1783       CompileTask::print(st, this, msg, /*short_form:*/ true);
1784       st->print_cr(" (" INTPTR_FORMAT ")", p2i(this));
1785     } else {
1786       CompileTask::print(st, this, msg, /*short_form:*/ false);
1787     }
1788   }
1789 }
1790 
1791 void nmethod::maybe_print_nmethod(const DirectiveSet* directive) {
1792   bool printnmethods = directive->PrintAssemblyOption || directive->PrintNMethodsOption;
1793   if (printnmethods || PrintDebugInfo || PrintRelocations || PrintDependencies || PrintExceptionHandlers) {
1794     print_nmethod(printnmethods);
1795   }
1796 }
1797 
1798 void nmethod::print_nmethod(bool printmethod) {
1799   // Enter a critical section to prevent a race with deopts that patch code and updates the relocation info.
1800   // Unfortunately, we have to lock the NMethodState_lock before the tty lock due to the deadlock rules and
1801   // cannot lock in a more finely grained manner.
1802   ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
1803   ttyLocker ttyl;  // keep the following output all in one block
1804   if (xtty != nullptr) {
1805     xtty->begin_head("print_nmethod");
1806     log_identity(xtty);
1807     xtty->stamp();
1808     xtty->end_head();
1809   }
1810   // Print the header part, then print the requested information.
1811   // This is both handled in decode2().
1812   if (printmethod) {
1813     ResourceMark m;
1814     if (is_compiled_by_c1()) {
1815       tty->cr();
1816       tty->print_cr("============================= C1-compiled nmethod ==============================");
1817     }
1818     if (is_compiled_by_jvmci()) {
1819       tty->cr();
1820       tty->print_cr("=========================== JVMCI-compiled nmethod =============================");
1821     }
1822     tty->print_cr("----------------------------------- Assembly -----------------------------------");
1823     decode2(tty);
1824 #if defined(SUPPORT_DATA_STRUCTS)
1825     if (AbstractDisassembler::show_structs()) {
1826       // Print the oops from the underlying CodeBlob as well.
1827       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1828       print_oops(tty);
1829       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1830       print_metadata(tty);
1831       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1832       print_pcs_on(tty);
1833       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1834       if (oop_maps() != nullptr) {
1835         tty->print("oop maps:"); // oop_maps()->print_on(tty) outputs a cr() at the beginning
1836         oop_maps()->print_on(tty);
1837         tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1838       }
1839     }
1840 #endif
1841   } else {
1842     print(); // print the header part only.
1843   }
1844 
1845 #if defined(SUPPORT_DATA_STRUCTS)
1846   if (AbstractDisassembler::show_structs()) {
1847     methodHandle mh(Thread::current(), _method);
1848     if (printmethod || PrintDebugInfo || CompilerOracle::has_option(mh, CompileCommandEnum::PrintDebugInfo)) {
1849       print_scopes();
1850       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1851     }
1852     if (printmethod || PrintRelocations || CompilerOracle::has_option(mh, CompileCommandEnum::PrintRelocations)) {
1853       print_relocations_on(tty);
1854       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1855     }
1856     if (printmethod || PrintDependencies || CompilerOracle::has_option(mh, CompileCommandEnum::PrintDependencies)) {
1857       print_dependencies_on(tty);
1858       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1859     }
1860     if (printmethod || PrintExceptionHandlers) {
1861       print_handler_table();
1862       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1863       print_nul_chk_table();
1864       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1865     }
1866 
1867     if (printmethod) {
1868       print_recorded_oops();
1869       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1870       print_recorded_metadata();
1871       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1872     }
1873   }
1874 #endif
1875 
1876   if (xtty != nullptr) {
1877     xtty->tail("print_nmethod");
1878   }
1879 }
1880 
1881 
1882 // Promote one word from an assembly-time handle to a live embedded oop.
1883 inline void nmethod::initialize_immediate_oop(oop* dest, jobject handle) {
1884   if (handle == nullptr ||
1885       // As a special case, IC oops are initialized to 1 or -1.
1886       handle == (jobject) Universe::non_oop_word()) {
1887     *(void**)dest = handle;
1888   } else {
1889     *dest = JNIHandles::resolve_non_null(handle);
1890   }
1891 }
1892 
1893 void nmethod::copy_values(GrowableArray<Handle>* array) {
1894   int length = array->length();
1895   assert((address)(oops_begin() + length) <= (address)oops_end(), "oops big enough");
1896   oop* dest = oops_begin();
1897   for (int index = 0 ; index < length; index++) {
1898     dest[index] = array->at(index)();
1899   }
1900 }
1901 
1902 // Have to have the same name because it's called by a template
1903 void nmethod::copy_values(GrowableArray<jobject>* array) {
1904   int length = array->length();
1905   assert((address)(oops_begin() + length) <= (address)oops_end(), "oops big enough");
1906   oop* dest = oops_begin();
1907   for (int index = 0 ; index < length; index++) {
1908     initialize_immediate_oop(&dest[index], array->at(index));
1909   }
1910 
1911   // Now we can fix up all the oops in the code.  We need to do this
1912   // in the code because the assembler uses jobjects as placeholders.
1913   // The code and relocations have already been initialized by the
1914   // CodeBlob constructor, so it is valid even at this early point to
1915   // iterate over relocations and patch the code.
1916   fix_oop_relocations(nullptr, nullptr, /*initialize_immediates=*/ true);
1917 }
1918 
1919 void nmethod::copy_values(GrowableArray<Metadata*>* array) {
1920   int length = array->length();
1921   assert((address)(metadata_begin() + length) <= (address)metadata_end(), "big enough");
1922   Metadata** dest = metadata_begin();
1923   for (int index = 0 ; index < length; index++) {
1924     dest[index] = array->at(index);
1925   }
1926 }
1927 
1928 void nmethod::fix_oop_relocations(address begin, address end, bool initialize_immediates) {
1929   // re-patch all oop-bearing instructions, just in case some oops moved
1930   RelocIterator iter(this, begin, end);
1931   while (iter.next()) {
1932     if (iter.type() == relocInfo::oop_type) {
1933       oop_Relocation* reloc = iter.oop_reloc();
1934       if (initialize_immediates && reloc->oop_is_immediate()) {
1935         oop* dest = reloc->oop_addr();
1936         jobject obj = *reinterpret_cast<jobject*>(dest);
1937         initialize_immediate_oop(dest, obj);
1938       }
1939       // Refresh the oop-related bits of this instruction.
1940       reloc->fix_oop_relocation();
1941     } else if (iter.type() == relocInfo::metadata_type) {
1942       metadata_Relocation* reloc = iter.metadata_reloc();
1943       reloc->fix_metadata_relocation();
1944     }
1945   }
1946 }
1947 
1948 void nmethod::create_reloc_immediates_list(JavaThread* thread, GrowableArray<Handle>& oop_list, GrowableArray<Metadata*>& metadata_list) {
1949   RelocIterator iter(this);
1950   while (iter.next()) {
1951     if (iter.type() == relocInfo::oop_type) {
1952       oop_Relocation* reloc = iter.oop_reloc();
1953       if (reloc->oop_is_immediate()) {
1954         oop dest = reloc->oop_value();
1955         Handle h(thread, dest);
1956         oop_list.append(h);
1957       }
1958     } else if (iter.type() == relocInfo::metadata_type) {
1959       metadata_Relocation* reloc = iter.metadata_reloc();
1960       if (reloc->metadata_is_immediate()) {
1961         Metadata* m = reloc->metadata_value();
1962         metadata_list.append(m);
1963       }
1964     }
1965   }
1966 }
1967 
1968 static void install_post_call_nop_displacement(nmethod* nm, address pc) {
1969   NativePostCallNop* nop = nativePostCallNop_at((address) pc);
1970   intptr_t cbaddr = (intptr_t) nm;
1971   intptr_t offset = ((intptr_t) pc) - cbaddr;
1972 
1973   int oopmap_slot = nm->oop_maps()->find_slot_for_offset(int((intptr_t) pc - (intptr_t) nm->code_begin()));
1974   if (oopmap_slot < 0) { // this can happen at asynchronous (non-safepoint) stackwalks
1975     log_debug(codecache)("failed to find oopmap for cb: " INTPTR_FORMAT " offset: %d", cbaddr, (int) offset);
1976   } else if (!nop->patch(oopmap_slot, offset)) {
1977     log_debug(codecache)("failed to encode %d %d", oopmap_slot, (int) offset);
1978   }
1979 }
1980 
1981 void nmethod::finalize_relocations() {
1982   NoSafepointVerifier nsv;
1983 
1984   GrowableArray<NativeMovConstReg*> virtual_call_data;
1985 
1986   // Make sure that post call nops fill in nmethod offsets eagerly so
1987   // we don't have to race with deoptimization
1988   RelocIterator iter(this);
1989   while (iter.next()) {
1990     if (iter.type() == relocInfo::virtual_call_type) {
1991       virtual_call_Relocation* r = iter.virtual_call_reloc();
1992       NativeMovConstReg* value = nativeMovConstReg_at(r->cached_value());
1993       virtual_call_data.append(value);
1994     } else if (iter.type() == relocInfo::post_call_nop_type) {
1995       post_call_nop_Relocation* const reloc = iter.post_call_nop_reloc();
1996       address pc = reloc->addr();
1997       install_post_call_nop_displacement(this, pc);
1998     }
1999   }
2000 
2001   if (virtual_call_data.length() > 0) {
2002     // We allocate a block of CompiledICData per nmethod so the GC can purge this faster.
2003     _compiled_ic_data = new CompiledICData[virtual_call_data.length()];
2004     CompiledICData* next_data = _compiled_ic_data;
2005 
2006     for (NativeMovConstReg* value : virtual_call_data) {
2007       value->set_data((intptr_t)next_data);
2008       next_data++;
2009     }
2010   }
2011 }
2012 
2013 void nmethod::make_deoptimized() {
2014   if (!Continuations::enabled()) {
2015     // Don't deopt this again.
2016     set_deoptimized_done();
2017     return;
2018   }
2019 
2020   assert(method() == nullptr || can_be_deoptimized(), "");
2021 
2022   CompiledICLocker ml(this);
2023   assert(CompiledICLocker::is_safe(this), "mt unsafe call");
2024 
2025   // If post call nops have been already patched, we can just bail-out.
2026   if (has_been_deoptimized()) {
2027     return;
2028   }
2029 
2030   ResourceMark rm;
2031   RelocIterator iter(this, oops_reloc_begin());
2032 
2033   while (iter.next()) {
2034 
2035     switch (iter.type()) {
2036       case relocInfo::virtual_call_type: {
2037         CompiledIC *ic = CompiledIC_at(&iter);
2038         address pc = ic->end_of_call();
2039         NativePostCallNop* nop = nativePostCallNop_at(pc);
2040         if (nop != nullptr) {
2041           nop->make_deopt();
2042         }
2043         assert(NativeDeoptInstruction::is_deopt_at(pc), "check");
2044         break;
2045       }
2046       case relocInfo::static_call_type:
2047       case relocInfo::opt_virtual_call_type: {
2048         CompiledDirectCall *csc = CompiledDirectCall::at(iter.reloc());
2049         address pc = csc->end_of_call();
2050         NativePostCallNop* nop = nativePostCallNop_at(pc);
2051         //tty->print_cr(" - static pc %p", pc);
2052         if (nop != nullptr) {
2053           nop->make_deopt();
2054         }
2055         // We can't assert here, there are some calls to stubs / runtime
2056         // that have reloc data and doesn't have a post call NOP.
2057         //assert(NativeDeoptInstruction::is_deopt_at(pc), "check");
2058         break;
2059       }
2060       default:
2061         break;
2062     }
2063   }
2064   // Don't deopt this again.
2065   set_deoptimized_done();
2066 }
2067 
2068 void nmethod::verify_clean_inline_caches() {
2069   assert(CompiledICLocker::is_safe(this), "mt unsafe call");
2070 
2071   ResourceMark rm;
2072   RelocIterator iter(this, oops_reloc_begin());
2073   while(iter.next()) {
2074     switch(iter.type()) {
2075       case relocInfo::virtual_call_type: {
2076         CompiledIC *ic = CompiledIC_at(&iter);
2077         CodeBlob *cb = CodeCache::find_blob(ic->destination());
2078         assert(cb != nullptr, "destination not in CodeBlob?");
2079         nmethod* nm = cb->as_nmethod_or_null();
2080         if (nm != nullptr) {
2081           // Verify that inline caches pointing to bad nmethods are clean
2082           if (!nm->is_in_use() || nm->is_unloading()) {
2083             assert(ic->is_clean(), "IC should be clean");
2084           }
2085         }
2086         break;
2087       }
2088       case relocInfo::static_call_type:
2089       case relocInfo::opt_virtual_call_type: {
2090         CompiledDirectCall *cdc = CompiledDirectCall::at(iter.reloc());
2091         CodeBlob *cb = CodeCache::find_blob(cdc->destination());
2092         assert(cb != nullptr, "destination not in CodeBlob?");
2093         nmethod* nm = cb->as_nmethod_or_null();
2094         if (nm != nullptr) {
2095           // Verify that inline caches pointing to bad nmethods are clean
2096           if (!nm->is_in_use() || nm->is_unloading() || nm->method()->code() != nm) {
2097             assert(cdc->is_clean(), "IC should be clean");
2098           }
2099         }
2100         break;
2101       }
2102       default:
2103         break;
2104     }
2105   }
2106 }
2107 
2108 void nmethod::mark_as_maybe_on_stack() {
2109   Atomic::store(&_gc_epoch, CodeCache::gc_epoch());
2110 }
2111 
2112 bool nmethod::is_maybe_on_stack() {
2113   // If the condition below is true, it means that the nmethod was found to
2114   // be alive the previous completed marking cycle.
2115   return Atomic::load(&_gc_epoch) >= CodeCache::previous_completed_gc_marking_cycle();
2116 }
2117 
2118 void nmethod::inc_decompile_count() {
2119   if (!is_compiled_by_c2() && !is_compiled_by_jvmci()) return;
2120   // Could be gated by ProfileTraps, but do not bother...
2121   Method* m = method();
2122   if (m == nullptr)  return;
2123   MethodData* mdo = m->method_data();
2124   if (mdo == nullptr)  return;
2125   // There is a benign race here.  See comments in methodData.hpp.
2126   mdo->inc_decompile_count();
2127 }
2128 
2129 void nmethod::inc_method_profiling_count() {
2130   Atomic::inc(&_method_profiling_count);
2131 }
2132 
2133 uint64_t nmethod::method_profiling_count() {
2134   return _method_profiling_count;
2135 }
2136 
2137 bool nmethod::try_transition(signed char new_state_int) {
2138   signed char new_state = new_state_int;
2139   assert_lock_strong(NMethodState_lock);
2140   signed char old_state = _state;
2141   if (old_state >= new_state) {
2142     // Ensure monotonicity of transitions.
2143     return false;
2144   }
2145   Atomic::store(&_state, new_state);
2146   return true;
2147 }
2148 
2149 void nmethod::invalidate_osr_method() {
2150   assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod");
2151   // Remove from list of active nmethods
2152   if (method() != nullptr) {
2153     method()->method_holder()->remove_osr_nmethod(this);
2154   }
2155 }
2156 
2157 void nmethod::log_state_change(const char* reason) const {
2158   assert(reason != nullptr, "Must provide a reason");
2159 
2160   if (LogCompilation) {
2161     if (xtty != nullptr) {
2162       ttyLocker ttyl;  // keep the following output all in one block
2163       xtty->begin_elem("make_not_entrant thread='%zu' reason='%s'",
2164                        os::current_thread_id(), reason);
2165       log_identity(xtty);
2166       xtty->stamp();
2167       xtty->end_elem();
2168     }
2169   }
2170 
2171   ResourceMark rm;
2172   stringStream ss(NEW_RESOURCE_ARRAY(char, 256), 256);
2173   ss.print("made not entrant: %s", reason);
2174 
2175   CompileTask::print_ul(this, ss.freeze());
2176   if (PrintCompilation) {
2177     print_on_with_msg(tty, ss.freeze());
2178   }
2179 }
2180 
2181 void nmethod::unlink_from_method() {
2182   if (method() != nullptr) {
2183     method()->unlink_code(this);
2184   }
2185 }
2186 
2187 // Invalidate code
2188 bool nmethod::make_not_entrant(const char* reason, bool make_not_entrant) {
2189   assert(reason != nullptr, "Must provide a reason");
2190 
2191   // This can be called while the system is already at a safepoint which is ok
2192   NoSafepointVerifier nsv;
2193 
2194   if (is_unloading()) {
2195     // If the nmethod is unloading, then it is already not entrant through
2196     // the nmethod entry barriers. No need to do anything; GC will unload it.
2197     return false;
2198   }
2199 
2200   if (Atomic::load(&_state) == not_entrant) {
2201     // Avoid taking the lock if already in required state.
2202     // This is safe from races because the state is an end-state,
2203     // which the nmethod cannot back out of once entered.
2204     // No need for fencing either.
2205     return false;
2206   }
2207 
2208   {
2209     // Enter critical section.  Does not block for safepoint.
2210     ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
2211 
2212     if (Atomic::load(&_state) == not_entrant) {
2213       // another thread already performed this transition so nothing
2214       // to do, but return false to indicate this.
2215       return false;
2216     }
2217 
2218     if (is_osr_method()) {
2219       // This logic is equivalent to the logic below for patching the
2220       // verified entry point of regular methods.
2221       // this effectively makes the osr nmethod not entrant
2222       invalidate_osr_method();
2223     } else {
2224       // The caller can be calling the method statically or through an inline
2225       // cache call.
2226       NativeJump::patch_verified_entry(entry_point(), verified_entry_point(),
2227                                        SharedRuntime::get_handle_wrong_method_stub());
2228 
2229       // Update the relocation info for the patched entry.
2230       // First, get the old relocation info...
2231       RelocIterator iter(this, verified_entry_point(), verified_entry_point() + 8);
2232       if (iter.next() && iter.addr() == verified_entry_point()) {
2233         Relocation* old_reloc = iter.reloc();
2234         // ...then reset the iterator to update it.
2235         RelocIterator iter(this, verified_entry_point(), verified_entry_point() + 8);
2236         relocInfo::change_reloc_info_for_address(&iter, verified_entry_point(), old_reloc->type(),
2237                                                  relocInfo::relocType::runtime_call_type);
2238       }
2239     }
2240 
2241     if (update_recompile_counts()) {
2242       // Mark the method as decompiled.
2243       inc_decompile_count();
2244     }
2245 
2246     BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2247     if (bs_nm == nullptr || !bs_nm->supports_entry_barrier(this)) {
2248       // If nmethod entry barriers are not supported, we won't mark
2249       // nmethods as on-stack when they become on-stack. So we
2250       // degrade to a less accurate flushing strategy, for now.
2251       mark_as_maybe_on_stack();
2252     }
2253 
2254     // Change state
2255     bool success = try_transition(not_entrant);
2256     assert(success, "Transition can't fail");
2257 
2258     // Log the transition once
2259     log_state_change(reason);
2260 
2261     // Remove nmethod from method.
2262     unlink_from_method();
2263 
2264     if (make_not_entrant) {
2265       // Keep cached code if it was simply replaced
2266       // otherwise make it not entrant too.
2267       AOTCodeCache::invalidate(_aot_code_entry);
2268     }
2269 
2270     CompileBroker::log_not_entrant(this);
2271   } // leave critical region under NMethodState_lock
2272 
2273 #if INCLUDE_JVMCI
2274   // Invalidate can't occur while holding the NMethodState_lock
2275   JVMCINMethodData* nmethod_data = jvmci_nmethod_data();
2276   if (nmethod_data != nullptr) {
2277     nmethod_data->invalidate_nmethod_mirror(this);
2278   }
2279 #endif
2280 
2281 #ifdef ASSERT
2282   if (is_osr_method() && method() != nullptr) {
2283     // Make sure osr nmethod is invalidated, i.e. not on the list
2284     bool found = method()->method_holder()->remove_osr_nmethod(this);
2285     assert(!found, "osr nmethod should have been invalidated");
2286   }
2287 #endif
2288 
2289   return true;
2290 }
2291 
2292 // For concurrent GCs, there must be a handshake between unlink and flush
2293 void nmethod::unlink() {
2294   if (is_unlinked()) {
2295     // Already unlinked.
2296     return;
2297   }
2298 
2299   flush_dependencies();
2300 
2301   // unlink_from_method will take the NMethodState_lock.
2302   // In this case we don't strictly need it when unlinking nmethods from
2303   // the Method, because it is only concurrently unlinked by
2304   // the entry barrier, which acquires the per nmethod lock.
2305   unlink_from_method();
2306 
2307   if (is_osr_method()) {
2308     invalidate_osr_method();
2309   }
2310 
2311 #if INCLUDE_JVMCI
2312   // Clear the link between this nmethod and a HotSpotNmethod mirror
2313   JVMCINMethodData* nmethod_data = jvmci_nmethod_data();
2314   if (nmethod_data != nullptr) {
2315     nmethod_data->invalidate_nmethod_mirror(this);
2316   }
2317 #endif
2318 
2319   // Post before flushing as jmethodID is being used
2320   post_compiled_method_unload();
2321 
2322   // Register for flushing when it is safe. For concurrent class unloading,
2323   // that would be after the unloading handshake, and for STW class unloading
2324   // that would be when getting back to the VM thread.
2325   ClassUnloadingContext::context()->register_unlinked_nmethod(this);
2326 }
2327 
2328 void nmethod::purge(bool unregister_nmethod) {
2329 
2330   MutexLocker ml(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2331 
2332   // completely deallocate this method
2333   Events::log_nmethod_flush(Thread::current(), "flushing %s nmethod " INTPTR_FORMAT, is_osr_method() ? "osr" : "", p2i(this));
2334   log_debug(codecache)("*flushing %s nmethod %3d/" INTPTR_FORMAT ". Live blobs:" UINT32_FORMAT
2335                        "/Free CodeCache:%zuKb",
2336                        is_osr_method() ? "osr" : "",_compile_id, p2i(this), CodeCache::blob_count(),
2337                        CodeCache::unallocated_capacity(CodeCache::get_code_blob_type(this))/1024);
2338 
2339   // We need to deallocate any ExceptionCache data.
2340   // Note that we do not need to grab the nmethod lock for this, it
2341   // better be thread safe if we're disposing of it!
2342   ExceptionCache* ec = exception_cache();
2343   while(ec != nullptr) {
2344     ExceptionCache* next = ec->next();
2345     delete ec;
2346     ec = next;
2347   }
2348   if (_pc_desc_container != nullptr) {
2349     delete _pc_desc_container;
2350   }
2351   if (_compiled_ic_data != nullptr) {
2352     delete[] _compiled_ic_data;
2353   }
2354 
2355   if (_immutable_data != data_end() && !AOTCodeCache::is_address_in_aot_cache((address)_oop_maps)) {
2356     os::free(_immutable_data);
2357     _immutable_data = blob_end(); // Valid not null address
2358   }
2359   if (unregister_nmethod) {
2360     Universe::heap()->unregister_nmethod(this);
2361   }
2362   CodeCache::unregister_old_nmethod(this);
2363 
2364   CodeBlob::purge();
2365 }
2366 
2367 oop nmethod::oop_at(int index) const {
2368   if (index == 0) {
2369     return nullptr;
2370   }
2371 
2372   BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2373   return bs_nm->oop_load_no_keepalive(this, index);
2374 }
2375 
2376 oop nmethod::oop_at_phantom(int index) const {
2377   if (index == 0) {
2378     return nullptr;
2379   }
2380 
2381   BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2382   return bs_nm->oop_load_phantom(this, index);
2383 }
2384 
2385 //
2386 // Notify all classes this nmethod is dependent on that it is no
2387 // longer dependent.
2388 
2389 void nmethod::flush_dependencies() {
2390   if (!has_flushed_dependencies()) {
2391     set_has_flushed_dependencies(true);
2392     for (Dependencies::DepStream deps(this); deps.next(); ) {
2393       if (deps.type() == Dependencies::call_site_target_value) {
2394         // CallSite dependencies are managed on per-CallSite instance basis.
2395         oop call_site = deps.argument_oop(0);
2396         MethodHandles::clean_dependency_context(call_site);
2397       } else {
2398         InstanceKlass* ik = deps.context_type();
2399         if (ik == nullptr) {
2400           continue;  // ignore things like evol_method
2401         }
2402         // During GC liveness of dependee determines class that needs to be updated.
2403         // The GC may clean dependency contexts concurrently and in parallel.
2404         ik->clean_dependency_context();
2405       }
2406     }
2407   }
2408 }
2409 
2410 void nmethod::post_compiled_method(CompileTask* task) {
2411   task->mark_success();
2412   task->set_nm_content_size(content_size());
2413   task->set_nm_insts_size(insts_size());
2414   task->set_nm_total_size(total_size());
2415 
2416   // task->is_aot() is true only for loaded cached code.
2417   // nmethod::_aot_code_entry is set for loaded and stored cached code
2418   // to invalidate the entry when nmethod is deoptimized.
2419   // There is option to not store in archive cached code.
2420   guarantee((_aot_code_entry != nullptr) || !task->is_aot() || VerifyCachedCode, "sanity");
2421 
2422   // JVMTI -- compiled method notification (must be done outside lock)
2423   post_compiled_method_load_event();
2424 
2425   if (CompilationLog::log() != nullptr) {
2426     CompilationLog::log()->log_nmethod(JavaThread::current(), this);
2427   }
2428 
2429   const DirectiveSet* directive = task->directive();
2430   maybe_print_nmethod(directive);
2431 }
2432 
2433 // ------------------------------------------------------------------
2434 // post_compiled_method_load_event
2435 // new method for install_code() path
2436 // Transfer information from compilation to jvmti
2437 void nmethod::post_compiled_method_load_event(JvmtiThreadState* state) {
2438   // This is a bad time for a safepoint.  We don't want
2439   // this nmethod to get unloaded while we're queueing the event.
2440   NoSafepointVerifier nsv;
2441 
2442   Method* m = method();
2443   HOTSPOT_COMPILED_METHOD_LOAD(
2444       (char *) m->klass_name()->bytes(),
2445       m->klass_name()->utf8_length(),
2446       (char *) m->name()->bytes(),
2447       m->name()->utf8_length(),
2448       (char *) m->signature()->bytes(),
2449       m->signature()->utf8_length(),
2450       insts_begin(), insts_size());
2451 
2452 
2453   if (JvmtiExport::should_post_compiled_method_load()) {
2454     // Only post unload events if load events are found.
2455     set_load_reported();
2456     // If a JavaThread hasn't been passed in, let the Service thread
2457     // (which is a real Java thread) post the event
2458     JvmtiDeferredEvent event = JvmtiDeferredEvent::compiled_method_load_event(this);
2459     if (state == nullptr) {
2460       // Execute any barrier code for this nmethod as if it's called, since
2461       // keeping it alive looks like stack walking.
2462       run_nmethod_entry_barrier();
2463       ServiceThread::enqueue_deferred_event(&event);
2464     } else {
2465       // This enters the nmethod barrier outside in the caller.
2466       state->enqueue_event(&event);
2467     }
2468   }
2469 }
2470 
2471 void nmethod::post_compiled_method_unload() {
2472   assert(_method != nullptr, "just checking");
2473   DTRACE_METHOD_UNLOAD_PROBE(method());
2474 
2475   // If a JVMTI agent has enabled the CompiledMethodUnload event then
2476   // post the event. The Method* will not be valid when this is freed.
2477 
2478   // Don't bother posting the unload if the load event wasn't posted.
2479   if (load_reported() && JvmtiExport::should_post_compiled_method_unload()) {
2480     JvmtiDeferredEvent event =
2481       JvmtiDeferredEvent::compiled_method_unload_event(
2482           method()->jmethod_id(), insts_begin());
2483     ServiceThread::enqueue_deferred_event(&event);
2484   }
2485 }
2486 
2487 // Iterate over metadata calling this function.   Used by RedefineClasses
2488 void nmethod::metadata_do(MetadataClosure* f) {
2489   {
2490     // Visit all immediate references that are embedded in the instruction stream.
2491     RelocIterator iter(this, oops_reloc_begin());
2492     while (iter.next()) {
2493       if (iter.type() == relocInfo::metadata_type) {
2494         metadata_Relocation* r = iter.metadata_reloc();
2495         // In this metadata, we must only follow those metadatas directly embedded in
2496         // the code.  Other metadatas (oop_index>0) are seen as part of
2497         // the metadata section below.
2498         assert(1 == (r->metadata_is_immediate()) +
2499                (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()),
2500                "metadata must be found in exactly one place");
2501         if (r->metadata_is_immediate() && r->metadata_value() != nullptr) {
2502           Metadata* md = r->metadata_value();
2503           if (md != _method) f->do_metadata(md);
2504         }
2505       } else if (iter.type() == relocInfo::virtual_call_type) {
2506         // Check compiledIC holders associated with this nmethod
2507         ResourceMark rm;
2508         CompiledIC *ic = CompiledIC_at(&iter);
2509         ic->metadata_do(f);
2510       }
2511     }
2512   }
2513 
2514   // Visit the metadata section
2515   for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
2516     if (*p == Universe::non_oop_word() || *p == nullptr)  continue;  // skip non-oops
2517     Metadata* md = *p;
2518     f->do_metadata(md);
2519   }
2520 
2521   // Visit metadata not embedded in the other places.
2522   if (_method != nullptr) f->do_metadata(_method);
2523 }
2524 
2525 // Heuristic for nuking nmethods even though their oops are live.
2526 // Main purpose is to reduce code cache pressure and get rid of
2527 // nmethods that don't seem to be all that relevant any longer.
2528 bool nmethod::is_cold() {
2529   if (!MethodFlushing || is_native_method() || is_not_installed()) {
2530     // No heuristic unloading at all
2531     return false;
2532   }
2533 
2534   if (!is_maybe_on_stack() && is_not_entrant()) {
2535     // Not entrant nmethods that are not on any stack can just
2536     // be removed
2537     return true;
2538   }
2539 
2540   BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2541   if (bs_nm == nullptr || !bs_nm->supports_entry_barrier(this)) {
2542     // On platforms that don't support nmethod entry barriers, we can't
2543     // trust the temporal aspect of the gc epochs. So we can't detect
2544     // cold nmethods on such platforms.
2545     return false;
2546   }
2547 
2548   if (!UseCodeCacheFlushing) {
2549     // Bail out if we don't heuristically remove nmethods
2550     return false;
2551   }
2552 
2553   // Other code can be phased out more gradually after N GCs
2554   return CodeCache::previous_completed_gc_marking_cycle() > _gc_epoch + 2 * CodeCache::cold_gc_count();
2555 }
2556 
2557 // The _is_unloading_state encodes a tuple comprising the unloading cycle
2558 // and the result of IsUnloadingBehaviour::is_unloading() for that cycle.
2559 // This is the bit layout of the _is_unloading_state byte: 00000CCU
2560 // CC refers to the cycle, which has 2 bits, and U refers to the result of
2561 // IsUnloadingBehaviour::is_unloading() for that unloading cycle.
2562 
2563 class IsUnloadingState: public AllStatic {
2564   static const uint8_t _is_unloading_mask = 1;
2565   static const uint8_t _is_unloading_shift = 0;
2566   static const uint8_t _unloading_cycle_mask = 6;
2567   static const uint8_t _unloading_cycle_shift = 1;
2568 
2569   static uint8_t set_is_unloading(uint8_t state, bool value) {
2570     state &= (uint8_t)~_is_unloading_mask;
2571     if (value) {
2572       state |= 1 << _is_unloading_shift;
2573     }
2574     assert(is_unloading(state) == value, "unexpected unloading cycle overflow");
2575     return state;
2576   }
2577 
2578   static uint8_t set_unloading_cycle(uint8_t state, uint8_t value) {
2579     state &= (uint8_t)~_unloading_cycle_mask;
2580     state |= (uint8_t)(value << _unloading_cycle_shift);
2581     assert(unloading_cycle(state) == value, "unexpected unloading cycle overflow");
2582     return state;
2583   }
2584 
2585 public:
2586   static bool is_unloading(uint8_t state) { return (state & _is_unloading_mask) >> _is_unloading_shift == 1; }
2587   static uint8_t unloading_cycle(uint8_t state) { return (state & _unloading_cycle_mask) >> _unloading_cycle_shift; }
2588 
2589   static uint8_t create(bool is_unloading, uint8_t unloading_cycle) {
2590     uint8_t state = 0;
2591     state = set_is_unloading(state, is_unloading);
2592     state = set_unloading_cycle(state, unloading_cycle);
2593     return state;
2594   }
2595 };
2596 
2597 bool nmethod::is_unloading() {
2598   uint8_t state = Atomic::load(&_is_unloading_state);
2599   bool state_is_unloading = IsUnloadingState::is_unloading(state);
2600   if (state_is_unloading) {
2601     return true;
2602   }
2603   uint8_t state_unloading_cycle = IsUnloadingState::unloading_cycle(state);
2604   uint8_t current_cycle = CodeCache::unloading_cycle();
2605   if (state_unloading_cycle == current_cycle) {
2606     return false;
2607   }
2608 
2609   // The IsUnloadingBehaviour is responsible for calculating if the nmethod
2610   // should be unloaded. This can be either because there is a dead oop,
2611   // or because is_cold() heuristically determines it is time to unload.
2612   state_unloading_cycle = current_cycle;
2613   state_is_unloading = IsUnloadingBehaviour::is_unloading(this);
2614   uint8_t new_state = IsUnloadingState::create(state_is_unloading, state_unloading_cycle);
2615 
2616   // Note that if an nmethod has dead oops, everyone will agree that the
2617   // nmethod is_unloading. However, the is_cold heuristics can yield
2618   // different outcomes, so we guard the computed result with a CAS
2619   // to ensure all threads have a shared view of whether an nmethod
2620   // is_unloading or not.
2621   uint8_t found_state = Atomic::cmpxchg(&_is_unloading_state, state, new_state, memory_order_relaxed);
2622 
2623   if (found_state == state) {
2624     // First to change state, we win
2625     return state_is_unloading;
2626   } else {
2627     // State already set, so use it
2628     return IsUnloadingState::is_unloading(found_state);
2629   }
2630 }
2631 
2632 void nmethod::clear_unloading_state() {
2633   uint8_t state = IsUnloadingState::create(false, CodeCache::unloading_cycle());
2634   Atomic::store(&_is_unloading_state, state);
2635 }
2636 
2637 
2638 // This is called at the end of the strong tracing/marking phase of a
2639 // GC to unload an nmethod if it contains otherwise unreachable
2640 // oops or is heuristically found to be not important.
2641 void nmethod::do_unloading(bool unloading_occurred) {
2642   // Make sure the oop's ready to receive visitors
2643   if (is_unloading()) {
2644     unlink();
2645   } else {
2646     unload_nmethod_caches(unloading_occurred);
2647     BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2648     if (bs_nm != nullptr) {
2649       bs_nm->disarm(this);
2650     }
2651   }
2652 }
2653 
2654 void nmethod::oops_do(OopClosure* f, bool allow_dead) {
2655   // Prevent extra code cache walk for platforms that don't have immediate oops.
2656   if (relocInfo::mustIterateImmediateOopsInCode()) {
2657     RelocIterator iter(this, oops_reloc_begin());
2658 
2659     while (iter.next()) {
2660       if (iter.type() == relocInfo::oop_type ) {
2661         oop_Relocation* r = iter.oop_reloc();
2662         // In this loop, we must only follow those oops directly embedded in
2663         // the code.  Other oops (oop_index>0) are seen as part of scopes_oops.
2664         assert(1 == (r->oop_is_immediate()) +
2665                (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
2666                "oop must be found in exactly one place");
2667         if (r->oop_is_immediate() && r->oop_value() != nullptr) {
2668           f->do_oop(r->oop_addr());
2669         }
2670       }
2671     }
2672   }
2673 
2674   // Scopes
2675   // This includes oop constants not inlined in the code stream.
2676   for (oop* p = oops_begin(); p < oops_end(); p++) {
2677     if (*p == Universe::non_oop_word())  continue;  // skip non-oops
2678     f->do_oop(p);
2679   }
2680 }
2681 
2682 void nmethod::follow_nmethod(OopIterateClosure* cl) {
2683   // Process oops in the nmethod
2684   oops_do(cl);
2685 
2686   // CodeCache unloading support
2687   mark_as_maybe_on_stack();
2688 
2689   BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2690   bs_nm->disarm(this);
2691 
2692   // There's an assumption made that this function is not used by GCs that
2693   // relocate objects, and therefore we don't call fix_oop_relocations.
2694 }
2695 
2696 nmethod* volatile nmethod::_oops_do_mark_nmethods;
2697 
2698 void nmethod::oops_do_log_change(const char* state) {
2699   LogTarget(Trace, gc, nmethod) lt;
2700   if (lt.is_enabled()) {
2701     LogStream ls(lt);
2702     CompileTask::print(&ls, this, state, true /* short_form */);
2703   }
2704 }
2705 
2706 bool nmethod::oops_do_try_claim() {
2707   if (oops_do_try_claim_weak_request()) {
2708     nmethod* result = oops_do_try_add_to_list_as_weak_done();
2709     assert(result == nullptr, "adding to global list as weak done must always succeed.");
2710     return true;
2711   }
2712   return false;
2713 }
2714 
2715 bool nmethod::oops_do_try_claim_weak_request() {
2716   assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2717 
2718   if ((_oops_do_mark_link == nullptr) &&
2719       (Atomic::replace_if_null(&_oops_do_mark_link, mark_link(this, claim_weak_request_tag)))) {
2720     oops_do_log_change("oops_do, mark weak request");
2721     return true;
2722   }
2723   return false;
2724 }
2725 
2726 void nmethod::oops_do_set_strong_done(nmethod* old_head) {
2727   _oops_do_mark_link = mark_link(old_head, claim_strong_done_tag);
2728 }
2729 
2730 nmethod::oops_do_mark_link* nmethod::oops_do_try_claim_strong_done() {
2731   assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2732 
2733   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));
2734   if (old_next == nullptr) {
2735     oops_do_log_change("oops_do, mark strong done");
2736   }
2737   return old_next;
2738 }
2739 
2740 nmethod::oops_do_mark_link* nmethod::oops_do_try_add_strong_request(nmethod::oops_do_mark_link* next) {
2741   assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2742   assert(next == mark_link(this, claim_weak_request_tag), "Should be claimed as weak");
2743 
2744   oops_do_mark_link* old_next = Atomic::cmpxchg(&_oops_do_mark_link, next, mark_link(this, claim_strong_request_tag));
2745   if (old_next == next) {
2746     oops_do_log_change("oops_do, mark strong request");
2747   }
2748   return old_next;
2749 }
2750 
2751 bool nmethod::oops_do_try_claim_weak_done_as_strong_done(nmethod::oops_do_mark_link* next) {
2752   assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2753   assert(extract_state(next) == claim_weak_done_tag, "Should be claimed as weak done");
2754 
2755   oops_do_mark_link* old_next = Atomic::cmpxchg(&_oops_do_mark_link, next, mark_link(extract_nmethod(next), claim_strong_done_tag));
2756   if (old_next == next) {
2757     oops_do_log_change("oops_do, mark weak done -> mark strong done");
2758     return true;
2759   }
2760   return false;
2761 }
2762 
2763 nmethod* nmethod::oops_do_try_add_to_list_as_weak_done() {
2764   assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2765 
2766   assert(extract_state(_oops_do_mark_link) == claim_weak_request_tag ||
2767          extract_state(_oops_do_mark_link) == claim_strong_request_tag,
2768          "must be but is nmethod " PTR_FORMAT " %u", p2i(extract_nmethod(_oops_do_mark_link)), extract_state(_oops_do_mark_link));
2769 
2770   nmethod* old_head = Atomic::xchg(&_oops_do_mark_nmethods, this);
2771   // Self-loop if needed.
2772   if (old_head == nullptr) {
2773     old_head = this;
2774   }
2775   // Try to install end of list and weak done tag.
2776   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)) {
2777     oops_do_log_change("oops_do, mark weak done");
2778     return nullptr;
2779   } else {
2780     return old_head;
2781   }
2782 }
2783 
2784 void nmethod::oops_do_add_to_list_as_strong_done() {
2785   assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2786 
2787   nmethod* old_head = Atomic::xchg(&_oops_do_mark_nmethods, this);
2788   // Self-loop if needed.
2789   if (old_head == nullptr) {
2790     old_head = this;
2791   }
2792   assert(_oops_do_mark_link == mark_link(this, claim_strong_done_tag), "must be but is nmethod " PTR_FORMAT " state %u",
2793          p2i(extract_nmethod(_oops_do_mark_link)), extract_state(_oops_do_mark_link));
2794 
2795   oops_do_set_strong_done(old_head);
2796 }
2797 
2798 void nmethod::oops_do_process_weak(OopsDoProcessor* p) {
2799   if (!oops_do_try_claim_weak_request()) {
2800     // Failed to claim for weak processing.
2801     oops_do_log_change("oops_do, mark weak request fail");
2802     return;
2803   }
2804 
2805   p->do_regular_processing(this);
2806 
2807   nmethod* old_head = oops_do_try_add_to_list_as_weak_done();
2808   if (old_head == nullptr) {
2809     return;
2810   }
2811   oops_do_log_change("oops_do, mark weak done fail");
2812   // Adding to global list failed, another thread added a strong request.
2813   assert(extract_state(_oops_do_mark_link) == claim_strong_request_tag,
2814          "must be but is %u", extract_state(_oops_do_mark_link));
2815 
2816   oops_do_log_change("oops_do, mark weak request -> mark strong done");
2817 
2818   oops_do_set_strong_done(old_head);
2819   // Do missing strong processing.
2820   p->do_remaining_strong_processing(this);
2821 }
2822 
2823 void nmethod::oops_do_process_strong(OopsDoProcessor* p) {
2824   oops_do_mark_link* next_raw = oops_do_try_claim_strong_done();
2825   if (next_raw == nullptr) {
2826     p->do_regular_processing(this);
2827     oops_do_add_to_list_as_strong_done();
2828     return;
2829   }
2830   // Claim failed. Figure out why and handle it.
2831   if (oops_do_has_weak_request(next_raw)) {
2832     oops_do_mark_link* old = next_raw;
2833     // Claim failed because being weak processed (state == "weak request").
2834     // Try to request deferred strong processing.
2835     next_raw = oops_do_try_add_strong_request(old);
2836     if (next_raw == old) {
2837       // Successfully requested deferred strong processing.
2838       return;
2839     }
2840     // Failed because of a concurrent transition. No longer in "weak request" state.
2841   }
2842   if (oops_do_has_any_strong_state(next_raw)) {
2843     // Already claimed for strong processing or requested for such.
2844     return;
2845   }
2846   if (oops_do_try_claim_weak_done_as_strong_done(next_raw)) {
2847     // Successfully claimed "weak done" as "strong done". Do the missing marking.
2848     p->do_remaining_strong_processing(this);
2849     return;
2850   }
2851   // Claim failed, some other thread got it.
2852 }
2853 
2854 void nmethod::oops_do_marking_prologue() {
2855   assert_at_safepoint();
2856 
2857   log_trace(gc, nmethod)("oops_do_marking_prologue");
2858   assert(_oops_do_mark_nmethods == nullptr, "must be empty");
2859 }
2860 
2861 void nmethod::oops_do_marking_epilogue() {
2862   assert_at_safepoint();
2863 
2864   nmethod* next = _oops_do_mark_nmethods;
2865   _oops_do_mark_nmethods = nullptr;
2866   if (next != nullptr) {
2867     nmethod* cur;
2868     do {
2869       cur = next;
2870       next = extract_nmethod(cur->_oops_do_mark_link);
2871       cur->_oops_do_mark_link = nullptr;
2872       DEBUG_ONLY(cur->verify_oop_relocations());
2873 
2874       LogTarget(Trace, gc, nmethod) lt;
2875       if (lt.is_enabled()) {
2876         LogStream ls(lt);
2877         CompileTask::print(&ls, cur, "oops_do, unmark", /*short_form:*/ true);
2878       }
2879       // End if self-loop has been detected.
2880     } while (cur != next);
2881   }
2882   log_trace(gc, nmethod)("oops_do_marking_epilogue");
2883 }
2884 
2885 inline bool includes(void* p, void* from, void* to) {
2886   return from <= p && p < to;
2887 }
2888 
2889 
2890 void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) {
2891   assert(count >= 2, "must be sentinel values, at least");
2892 
2893 #ifdef ASSERT
2894   // must be sorted and unique; we do a binary search in find_pc_desc()
2895   int prev_offset = pcs[0].pc_offset();
2896   assert(prev_offset == PcDesc::lower_offset_limit,
2897          "must start with a sentinel");
2898   for (int i = 1; i < count; i++) {
2899     int this_offset = pcs[i].pc_offset();
2900     assert(this_offset > prev_offset, "offsets must be sorted");
2901     prev_offset = this_offset;
2902   }
2903   assert(prev_offset == PcDesc::upper_offset_limit,
2904          "must end with a sentinel");
2905 #endif //ASSERT
2906 
2907   // Search for MethodHandle invokes and tag the nmethod.
2908   for (int i = 0; i < count; i++) {
2909     if (pcs[i].is_method_handle_invoke()) {
2910       set_has_method_handle_invokes(true);
2911       break;
2912     }
2913   }
2914   assert(has_method_handle_invokes() == (_deopt_mh_handler_offset != -1), "must have deopt mh handler");
2915 
2916   int size = count * sizeof(PcDesc);
2917   assert(scopes_pcs_size() >= size, "oob");
2918   memcpy(scopes_pcs_begin(), pcs, size);
2919 
2920   // Adjust the final sentinel downward.
2921   PcDesc* last_pc = &scopes_pcs_begin()[count-1];
2922   assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity");
2923   last_pc->set_pc_offset(content_size() + 1);
2924   for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) {
2925     // Fill any rounding gaps with copies of the last record.
2926     last_pc[1] = last_pc[0];
2927   }
2928   // The following assert could fail if sizeof(PcDesc) is not
2929   // an integral multiple of oopSize (the rounding term).
2930   // If it fails, change the logic to always allocate a multiple
2931   // of sizeof(PcDesc), and fill unused words with copies of *last_pc.
2932   assert(last_pc + 1 == scopes_pcs_end(), "must match exactly");
2933 }
2934 
2935 void nmethod::copy_scopes_data(u_char* buffer, int size) {
2936   assert(scopes_data_size() >= size, "oob");
2937   memcpy(scopes_data_begin(), buffer, size);
2938 }
2939 
2940 #ifdef ASSERT
2941 static PcDesc* linear_search(int pc_offset, bool approximate, PcDesc* lower, PcDesc* upper) {
2942   PcDesc* res = nullptr;
2943   assert(lower != nullptr && lower->pc_offset() == PcDesc::lower_offset_limit,
2944          "must start with a sentinel");
2945   // lower + 1 to exclude initial sentinel
2946   for (PcDesc* p = lower + 1; p < upper; p++) {
2947     NOT_PRODUCT(--pc_nmethod_stats.pc_desc_tests);  // don't count this call to match_desc
2948     if (match_desc(p, pc_offset, approximate)) {
2949       if (res == nullptr) {
2950         res = p;
2951       } else {
2952         res = (PcDesc*) badAddress;
2953       }
2954     }
2955   }
2956   return res;
2957 }
2958 #endif
2959 
2960 
2961 #ifndef PRODUCT
2962 // Version of method to collect statistic
2963 PcDesc* PcDescContainer::find_pc_desc(address pc, bool approximate, address code_begin,
2964                                       PcDesc* lower, PcDesc* upper) {
2965   ++pc_nmethod_stats.pc_desc_queries;
2966   if (approximate) ++pc_nmethod_stats.pc_desc_approx;
2967 
2968   PcDesc* desc = _pc_desc_cache.last_pc_desc();
2969   assert(desc != nullptr, "PcDesc cache should be initialized already");
2970   if (desc->pc_offset() == (pc - code_begin)) {
2971     // Cached value matched
2972     ++pc_nmethod_stats.pc_desc_tests;
2973     ++pc_nmethod_stats.pc_desc_repeats;
2974     return desc;
2975   }
2976   return find_pc_desc_internal(pc, approximate, code_begin, lower, upper);
2977 }
2978 #endif
2979 
2980 // Finds a PcDesc with real-pc equal to "pc"
2981 PcDesc* PcDescContainer::find_pc_desc_internal(address pc, bool approximate, address code_begin,
2982                                                PcDesc* lower_incl, PcDesc* upper_incl) {
2983   if ((pc < code_begin) ||
2984       (pc - code_begin) >= (ptrdiff_t) PcDesc::upper_offset_limit) {
2985     return nullptr;  // PC is wildly out of range
2986   }
2987   int pc_offset = (int) (pc - code_begin);
2988 
2989   // Check the PcDesc cache if it contains the desired PcDesc
2990   // (This as an almost 100% hit rate.)
2991   PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate);
2992   if (res != nullptr) {
2993     assert(res == linear_search(pc_offset, approximate, lower_incl, upper_incl), "cache ok");
2994     return res;
2995   }
2996 
2997   // Fallback algorithm: quasi-linear search for the PcDesc
2998   // Find the last pc_offset less than the given offset.
2999   // The successor must be the required match, if there is a match at all.
3000   // (Use a fixed radix to avoid expensive affine pointer arithmetic.)
3001   PcDesc* lower = lower_incl;     // this is initial sentinel
3002   PcDesc* upper = upper_incl - 1; // exclude final sentinel
3003   if (lower >= upper)  return nullptr;  // no PcDescs at all
3004 
3005 #define assert_LU_OK \
3006   /* invariant on lower..upper during the following search: */ \
3007   assert(lower->pc_offset() <  pc_offset, "sanity"); \
3008   assert(upper->pc_offset() >= pc_offset, "sanity")
3009   assert_LU_OK;
3010 
3011   // Use the last successful return as a split point.
3012   PcDesc* mid = _pc_desc_cache.last_pc_desc();
3013   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
3014   if (mid->pc_offset() < pc_offset) {
3015     lower = mid;
3016   } else {
3017     upper = mid;
3018   }
3019 
3020   // Take giant steps at first (4096, then 256, then 16, then 1)
3021   const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ DEBUG_ONLY(-1);
3022   const int RADIX = (1 << LOG2_RADIX);
3023   for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) {
3024     while ((mid = lower + step) < upper) {
3025       assert_LU_OK;
3026       NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
3027       if (mid->pc_offset() < pc_offset) {
3028         lower = mid;
3029       } else {
3030         upper = mid;
3031         break;
3032       }
3033     }
3034     assert_LU_OK;
3035   }
3036 
3037   // Sneak up on the value with a linear search of length ~16.
3038   while (true) {
3039     assert_LU_OK;
3040     mid = lower + 1;
3041     NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
3042     if (mid->pc_offset() < pc_offset) {
3043       lower = mid;
3044     } else {
3045       upper = mid;
3046       break;
3047     }
3048   }
3049 #undef assert_LU_OK
3050 
3051   if (match_desc(upper, pc_offset, approximate)) {
3052     assert(upper == linear_search(pc_offset, approximate, lower_incl, upper_incl), "search mismatch");
3053     if (!Thread::current_in_asgct()) {
3054       // we don't want to modify the cache if we're in ASGCT
3055       // which is typically called in a signal handler
3056       _pc_desc_cache.add_pc_desc(upper);
3057     }
3058     return upper;
3059   } else {
3060     assert(nullptr == linear_search(pc_offset, approximate, lower_incl, upper_incl), "search mismatch");
3061     return nullptr;
3062   }
3063 }
3064 
3065 bool nmethod::check_dependency_on(DepChange& changes) {
3066   // What has happened:
3067   // 1) a new class dependee has been added
3068   // 2) dependee and all its super classes have been marked
3069   bool found_check = false;  // set true if we are upset
3070   for (Dependencies::DepStream deps(this); deps.next(); ) {
3071     // Evaluate only relevant dependencies.
3072     if (deps.spot_check_dependency_at(changes) != nullptr) {
3073       found_check = true;
3074       NOT_DEBUG(break);
3075     }
3076   }
3077   return found_check;
3078 }
3079 
3080 // Called from mark_for_deoptimization, when dependee is invalidated.
3081 bool nmethod::is_dependent_on_method(Method* dependee) {
3082   for (Dependencies::DepStream deps(this); deps.next(); ) {
3083     if (deps.type() != Dependencies::evol_method)
3084       continue;
3085     Method* method = deps.method_argument(0);
3086     if (method == dependee) return true;
3087   }
3088   return false;
3089 }
3090 
3091 void nmethod_init() {
3092   // make sure you didn't forget to adjust the filler fields
3093   assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word");
3094 }
3095 
3096 // -----------------------------------------------------------------------------
3097 // Verification
3098 
3099 class VerifyOopsClosure: public OopClosure {
3100   nmethod* _nm;
3101   bool     _ok;
3102 public:
3103   VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { }
3104   bool ok() { return _ok; }
3105   virtual void do_oop(oop* p) {
3106     if (oopDesc::is_oop_or_null(*p)) return;
3107     // Print diagnostic information before calling print_nmethod().
3108     // Assertions therein might prevent call from returning.
3109     tty->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)",
3110                   p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm));
3111     if (_ok) {
3112       _nm->print_nmethod(true);
3113       _ok = false;
3114     }
3115   }
3116   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
3117 };
3118 
3119 class VerifyMetadataClosure: public MetadataClosure {
3120  public:
3121   void do_metadata(Metadata* md) {
3122     if (md->is_method()) {
3123       Method* method = (Method*)md;
3124       assert(!method->is_old(), "Should not be installing old methods");
3125     }
3126   }
3127 };
3128 
3129 
3130 void nmethod::verify() {
3131   if (is_not_entrant())
3132     return;
3133 
3134   // Make sure all the entry points are correctly aligned for patching.
3135   NativeJump::check_verified_entry_alignment(entry_point(), verified_entry_point());
3136 
3137   // assert(oopDesc::is_oop(method()), "must be valid");
3138 
3139   ResourceMark rm;
3140 
3141   if (!CodeCache::contains(this)) {
3142     fatal("nmethod at " INTPTR_FORMAT " not in zone", p2i(this));
3143   }
3144 
3145   if(is_native_method() )
3146     return;
3147 
3148   nmethod* nm = CodeCache::find_nmethod(verified_entry_point());
3149   if (nm != this) {
3150     fatal("find_nmethod did not find this nmethod (" INTPTR_FORMAT ")", p2i(this));
3151   }
3152 
3153   // Verification can triggered during shutdown after AOTCodeCache is closed.
3154   // If the Scopes data is in the AOT code cache, then we should avoid verification during shutdown.
3155   if (!is_aot() || AOTCodeCache::is_on()) {
3156     for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3157       if (! p->verify(this)) {
3158         tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", p2i(this));
3159       }
3160     }
3161 
3162 #ifdef ASSERT
3163 #if INCLUDE_JVMCI
3164     {
3165       // Verify that implicit exceptions that deoptimize have a PcDesc and OopMap
3166       ImmutableOopMapSet* oms = oop_maps();
3167       ImplicitExceptionTable implicit_table(this);
3168       for (uint i = 0; i < implicit_table.len(); i++) {
3169         int exec_offset = (int) implicit_table.get_exec_offset(i);
3170         if (implicit_table.get_exec_offset(i) == implicit_table.get_cont_offset(i)) {
3171           assert(pc_desc_at(code_begin() + exec_offset) != nullptr, "missing PcDesc");
3172           bool found = false;
3173           for (int i = 0, imax = oms->count(); i < imax; i++) {
3174             if (oms->pair_at(i)->pc_offset() == exec_offset) {
3175               found = true;
3176               break;
3177             }
3178           }
3179           assert(found, "missing oopmap");
3180         }
3181       }
3182     }
3183 #endif
3184 #endif
3185   }
3186 
3187   VerifyOopsClosure voc(this);
3188   oops_do(&voc);
3189   assert(voc.ok(), "embedded oops must be OK");
3190   Universe::heap()->verify_nmethod(this);
3191 
3192   assert(_oops_do_mark_link == nullptr, "_oops_do_mark_link for %s should be nullptr but is " PTR_FORMAT,
3193          nm->method()->external_name(), p2i(_oops_do_mark_link));
3194   if (!is_aot() || AOTCodeCache::is_on()) {
3195     verify_scopes();
3196   }
3197 
3198   CompiledICLocker nm_verify(this);
3199   VerifyMetadataClosure vmc;
3200   metadata_do(&vmc);
3201 }
3202 
3203 
3204 void nmethod::verify_interrupt_point(address call_site, bool is_inline_cache) {
3205 
3206   // Verify IC only when nmethod installation is finished.
3207   if (!is_not_installed()) {
3208     if (CompiledICLocker::is_safe(this)) {
3209       if (is_inline_cache) {
3210         CompiledIC_at(this, call_site);
3211       } else {
3212         CompiledDirectCall::at(call_site);
3213       }
3214     } else {
3215       CompiledICLocker ml_verify(this);
3216       if (is_inline_cache) {
3217         CompiledIC_at(this, call_site);
3218       } else {
3219         CompiledDirectCall::at(call_site);
3220       }
3221     }
3222   }
3223 
3224   HandleMark hm(Thread::current());
3225 
3226   PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address());
3227   assert(pd != nullptr, "PcDesc must exist");
3228   for (ScopeDesc* sd = new ScopeDesc(this, pd);
3229        !sd->is_top(); sd = sd->sender()) {
3230     sd->verify();
3231   }
3232 }
3233 
3234 void nmethod::verify_scopes() {
3235   if( !method() ) return;       // Runtime stubs have no scope
3236   if (method()->is_native()) return; // Ignore stub methods.
3237   // iterate through all interrupt point
3238   // and verify the debug information is valid.
3239   RelocIterator iter(this);
3240   while (iter.next()) {
3241     address stub = nullptr;
3242     switch (iter.type()) {
3243       case relocInfo::virtual_call_type:
3244         verify_interrupt_point(iter.addr(), true /* is_inline_cache */);
3245         break;
3246       case relocInfo::opt_virtual_call_type:
3247         stub = iter.opt_virtual_call_reloc()->static_stub();
3248         verify_interrupt_point(iter.addr(), false /* is_inline_cache */);
3249         break;
3250       case relocInfo::static_call_type:
3251         stub = iter.static_call_reloc()->static_stub();
3252         verify_interrupt_point(iter.addr(), false /* is_inline_cache */);
3253         break;
3254       case relocInfo::runtime_call_type:
3255       case relocInfo::runtime_call_w_cp_type: {
3256         address destination = iter.reloc()->value();
3257         // Right now there is no way to find out which entries support
3258         // an interrupt point.  It would be nice if we had this
3259         // information in a table.
3260         break;
3261       }
3262       default:
3263         break;
3264     }
3265     assert(stub == nullptr || stub_contains(stub), "static call stub outside stub section");
3266   }
3267 }
3268 
3269 
3270 // -----------------------------------------------------------------------------
3271 // Printing operations
3272 
3273 void nmethod::print_on_impl(outputStream* st) const {
3274   ResourceMark rm;
3275 
3276   st->print("Compiled method ");
3277 
3278   if (is_compiled_by_c1()) {
3279     st->print("(c1) ");
3280   } else if (is_compiled_by_c2()) {
3281     st->print("(c2) ");
3282   } else if (is_compiled_by_jvmci()) {
3283     st->print("(JVMCI) ");
3284   } else {
3285     st->print("(n/a) ");
3286   }
3287 
3288   print_on_with_msg(st, nullptr);
3289 
3290   if (WizardMode) {
3291     st->print("((nmethod*) " INTPTR_FORMAT ") ", p2i(this));
3292     st->print(" for method " INTPTR_FORMAT , p2i(method()));
3293     st->print(" { ");
3294     st->print_cr("%s ", state());
3295     st->print_cr("}:");
3296   }
3297   if (size              () > 0) st->print_cr(" total in heap  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3298                                              p2i(this),
3299                                              p2i(this) + size(),
3300                                              size());
3301   if (consts_size       () > 0) st->print_cr(" constants      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3302                                              p2i(consts_begin()),
3303                                              p2i(consts_end()),
3304                                              consts_size());
3305   if (insts_size        () > 0) st->print_cr(" main code      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3306                                              p2i(insts_begin()),
3307                                              p2i(insts_end()),
3308                                              insts_size());
3309   if (stub_size         () > 0) st->print_cr(" stub code      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3310                                              p2i(stub_begin()),
3311                                              p2i(stub_end()),
3312                                              stub_size());
3313   if (oops_size         () > 0) st->print_cr(" oops           [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3314                                              p2i(oops_begin()),
3315                                              p2i(oops_end()),
3316                                              oops_size());
3317   if (mutable_data_size() > 0) st->print_cr(" mutable data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3318                                              p2i(mutable_data_begin()),
3319                                              p2i(mutable_data_end()),
3320                                              mutable_data_size());
3321   if (relocation_size() > 0)   st->print_cr(" relocation     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3322                                              p2i(relocation_begin()),
3323                                              p2i(relocation_end()),
3324                                              relocation_size());
3325   if (metadata_size     () > 0) st->print_cr(" metadata       [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3326                                              p2i(metadata_begin()),
3327                                              p2i(metadata_end()),
3328                                              metadata_size());
3329 #if INCLUDE_JVMCI
3330   if (jvmci_data_size   () > 0) st->print_cr(" JVMCI data     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3331                                              p2i(jvmci_data_begin()),
3332                                              p2i(jvmci_data_end()),
3333                                              jvmci_data_size());
3334 #endif
3335   if (immutable_data_size() > 0) st->print_cr(" immutable data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3336                                              p2i(immutable_data_begin()),
3337                                              p2i(immutable_data_end()),
3338                                              immutable_data_size());
3339   if (dependencies_size () > 0) st->print_cr(" dependencies   [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3340                                              p2i(dependencies_begin()),
3341                                              p2i(dependencies_end()),
3342                                              dependencies_size());
3343   if (nul_chk_table_size() > 0) st->print_cr(" nul chk table  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3344                                              p2i(nul_chk_table_begin()),
3345                                              p2i(nul_chk_table_end()),
3346                                              nul_chk_table_size());
3347   if (handler_table_size() > 0) st->print_cr(" handler table  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3348                                              p2i(handler_table_begin()),
3349                                              p2i(handler_table_end()),
3350                                              handler_table_size());
3351   if (scopes_pcs_size   () > 0) st->print_cr(" scopes pcs     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3352                                              p2i(scopes_pcs_begin()),
3353                                              p2i(scopes_pcs_end()),
3354                                              scopes_pcs_size());
3355   if (scopes_data_size  () > 0) st->print_cr(" scopes data    [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3356                                              p2i(scopes_data_begin()),
3357                                              p2i(scopes_data_end()),
3358                                              scopes_data_size());
3359 #if INCLUDE_JVMCI
3360   if (speculations_size () > 0) st->print_cr(" speculations   [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3361                                              p2i(speculations_begin()),
3362                                              p2i(speculations_end()),
3363                                              speculations_size());
3364 #endif
3365   if (AOTCodeCache::is_on() && _aot_code_entry != nullptr) {
3366     _aot_code_entry->print(st);
3367   }
3368 }
3369 
3370 void nmethod::print_code() {
3371   ResourceMark m;
3372   ttyLocker ttyl;
3373   // Call the specialized decode method of this class.
3374   decode(tty);
3375 }
3376 
3377 #ifndef PRODUCT  // called InstanceKlass methods are available only then. Declared as PRODUCT_RETURN
3378 
3379 void nmethod::print_dependencies_on(outputStream* out) {
3380   ResourceMark rm;
3381   stringStream st;
3382   st.print_cr("Dependencies:");
3383   for (Dependencies::DepStream deps(this); deps.next(); ) {
3384     deps.print_dependency(&st);
3385     InstanceKlass* ctxk = deps.context_type();
3386     if (ctxk != nullptr) {
3387       if (ctxk->is_dependent_nmethod(this)) {
3388         st.print_cr("   [nmethod<=klass]%s", ctxk->external_name());
3389       }
3390     }
3391     deps.log_dependency();  // put it into the xml log also
3392   }
3393   out->print_raw(st.as_string());
3394 }
3395 #endif
3396 
3397 #if defined(SUPPORT_DATA_STRUCTS)
3398 
3399 // Print the oops from the underlying CodeBlob.
3400 void nmethod::print_oops(outputStream* st) {
3401   ResourceMark m;
3402   st->print("Oops:");
3403   if (oops_begin() < oops_end()) {
3404     st->cr();
3405     for (oop* p = oops_begin(); p < oops_end(); p++) {
3406       Disassembler::print_location((unsigned char*)p, (unsigned char*)oops_begin(), (unsigned char*)oops_end(), st, true, false);
3407       st->print(PTR_FORMAT " ", *((uintptr_t*)p));
3408       if (Universe::contains_non_oop_word(p)) {
3409         st->print_cr("NON_OOP");
3410         continue;  // skip non-oops
3411       }
3412       if (*p == nullptr) {
3413         st->print_cr("nullptr-oop");
3414         continue;  // skip non-oops
3415       }
3416       (*p)->print_value_on(st);
3417       st->cr();
3418     }
3419   } else {
3420     st->print_cr(" <list empty>");
3421   }
3422 }
3423 
3424 // Print metadata pool.
3425 void nmethod::print_metadata(outputStream* st) {
3426   ResourceMark m;
3427   st->print("Metadata:");
3428   if (metadata_begin() < metadata_end()) {
3429     st->cr();
3430     for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
3431       Disassembler::print_location((unsigned char*)p, (unsigned char*)metadata_begin(), (unsigned char*)metadata_end(), st, true, false);
3432       st->print(PTR_FORMAT " ", *((uintptr_t*)p));
3433       if (*p && *p != Universe::non_oop_word()) {
3434         (*p)->print_value_on(st);
3435       }
3436       st->cr();
3437     }
3438   } else {
3439     st->print_cr(" <list empty>");
3440   }
3441 }
3442 
3443 #ifndef PRODUCT  // ScopeDesc::print_on() is available only then. Declared as PRODUCT_RETURN
3444 void nmethod::print_scopes_on(outputStream* st) {
3445   // Find the first pc desc for all scopes in the code and print it.
3446   ResourceMark rm;
3447   st->print("scopes:");
3448   if (scopes_pcs_begin() < scopes_pcs_end()) {
3449     st->cr();
3450     for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3451       if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null)
3452         continue;
3453 
3454       ScopeDesc* sd = scope_desc_at(p->real_pc(this));
3455       while (sd != nullptr) {
3456         sd->print_on(st, p);  // print output ends with a newline
3457         sd = sd->sender();
3458       }
3459     }
3460   } else {
3461     st->print_cr(" <list empty>");
3462   }
3463 }
3464 #endif
3465 
3466 #ifndef PRODUCT  // RelocIterator does support printing only then.
3467 void nmethod::print_relocations_on(outputStream* st) {
3468   ResourceMark m;       // in case methods get printed via the debugger
3469   st->print_cr("relocations:");
3470   RelocIterator iter(this);
3471   iter.print_on(st);
3472 }
3473 #endif
3474 
3475 void nmethod::print_pcs_on(outputStream* st) {
3476   ResourceMark m;       // in case methods get printed via debugger
3477   st->print("pc-bytecode offsets:");
3478   if (scopes_pcs_begin() < scopes_pcs_end()) {
3479     st->cr();
3480     for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3481       p->print_on(st, this);  // print output ends with a newline
3482     }
3483   } else {
3484     st->print_cr(" <list empty>");
3485   }
3486 }
3487 
3488 void nmethod::print_handler_table() {
3489   ExceptionHandlerTable(this).print(code_begin());
3490 }
3491 
3492 void nmethod::print_nul_chk_table() {
3493   ImplicitExceptionTable(this).print(code_begin());
3494 }
3495 
3496 void nmethod::print_recorded_oop(int log_n, int i) {
3497   void* value;
3498 
3499   if (i == 0) {
3500     value = nullptr;
3501   } else {
3502     // Be careful around non-oop words. Don't create an oop
3503     // with that value, or it will assert in verification code.
3504     if (Universe::contains_non_oop_word(oop_addr_at(i))) {
3505       value = Universe::non_oop_word();
3506     } else {
3507       value = oop_at(i);
3508     }
3509   }
3510 
3511   tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(value));
3512 
3513   if (value == Universe::non_oop_word()) {
3514     tty->print("non-oop word");
3515   } else {
3516     if (value == nullptr) {
3517       tty->print("nullptr-oop");
3518     } else {
3519       oop_at(i)->print_value_on(tty);
3520     }
3521   }
3522 
3523   tty->cr();
3524 }
3525 
3526 void nmethod::print_recorded_oops() {
3527   const int n = oops_count();
3528   const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6;
3529   tty->print("Recorded oops:");
3530   if (n > 0) {
3531     tty->cr();
3532     for (int i = 0; i < n; i++) {
3533       print_recorded_oop(log_n, i);
3534     }
3535   } else {
3536     tty->print_cr(" <list empty>");
3537   }
3538 }
3539 
3540 void nmethod::print_recorded_metadata() {
3541   const int n = metadata_count();
3542   const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6;
3543   tty->print("Recorded metadata:");
3544   if (n > 0) {
3545     tty->cr();
3546     for (int i = 0; i < n; i++) {
3547       Metadata* m = metadata_at(i);
3548       tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(m));
3549       if (m == (Metadata*)Universe::non_oop_word()) {
3550         tty->print("non-metadata word");
3551       } else if (m == nullptr) {
3552         tty->print("nullptr-oop");
3553       } else {
3554         Metadata::print_value_on_maybe_null(tty, m);
3555       }
3556       tty->cr();
3557     }
3558   } else {
3559     tty->print_cr(" <list empty>");
3560   }
3561 }
3562 #endif
3563 
3564 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
3565 
3566 void nmethod::print_constant_pool(outputStream* st) {
3567   //-----------------------------------
3568   //---<  Print the constant pool  >---
3569   //-----------------------------------
3570   int consts_size = this->consts_size();
3571   if ( consts_size > 0 ) {
3572     unsigned char* cstart = this->consts_begin();
3573     unsigned char* cp     = cstart;
3574     unsigned char* cend   = cp + consts_size;
3575     unsigned int   bytes_per_line = 4;
3576     unsigned int   CP_alignment   = 8;
3577     unsigned int   n;
3578 
3579     st->cr();
3580 
3581     //---<  print CP header to make clear what's printed  >---
3582     if( ((uintptr_t)cp&(CP_alignment-1)) == 0 ) {
3583       n = bytes_per_line;
3584       st->print_cr("[Constant Pool]");
3585       Disassembler::print_location(cp, cstart, cend, st, true, true);
3586       Disassembler::print_hexdata(cp, n, st, true);
3587       st->cr();
3588     } else {
3589       n = (int)((uintptr_t)cp & (bytes_per_line-1));
3590       st->print_cr("[Constant Pool (unaligned)]");
3591     }
3592 
3593     //---<  print CP contents, bytes_per_line at a time  >---
3594     while (cp < cend) {
3595       Disassembler::print_location(cp, cstart, cend, st, true, false);
3596       Disassembler::print_hexdata(cp, n, st, false);
3597       cp += n;
3598       n   = bytes_per_line;
3599       st->cr();
3600     }
3601 
3602     //---<  Show potential alignment gap between constant pool and code  >---
3603     cend = code_begin();
3604     if( cp < cend ) {
3605       n = 4;
3606       st->print_cr("[Code entry alignment]");
3607       while (cp < cend) {
3608         Disassembler::print_location(cp, cstart, cend, st, false, false);
3609         cp += n;
3610         st->cr();
3611       }
3612     }
3613   } else {
3614     st->print_cr("[Constant Pool (empty)]");
3615   }
3616   st->cr();
3617 }
3618 
3619 #endif
3620 
3621 // Disassemble this nmethod.
3622 // Print additional debug information, if requested. This could be code
3623 // comments, block comments, profiling counters, etc.
3624 // The undisassembled format is useful no disassembler library is available.
3625 // The resulting hex dump (with markers) can be disassembled later, or on
3626 // another system, when/where a disassembler library is available.
3627 void nmethod::decode2(outputStream* ost) const {
3628 
3629   // Called from frame::back_trace_with_decode without ResourceMark.
3630   ResourceMark rm;
3631 
3632   // Make sure we have a valid stream to print on.
3633   outputStream* st = ost ? ost : tty;
3634 
3635 #if defined(SUPPORT_ABSTRACT_ASSEMBLY) && ! defined(SUPPORT_ASSEMBLY)
3636   const bool use_compressed_format    = true;
3637   const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() ||
3638                                                                   AbstractDisassembler::show_block_comment());
3639 #else
3640   const bool use_compressed_format    = Disassembler::is_abstract();
3641   const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() ||
3642                                                                   AbstractDisassembler::show_block_comment());
3643 #endif
3644 
3645   st->cr();
3646   this->print_on(st);
3647   st->cr();
3648 
3649 #if defined(SUPPORT_ASSEMBLY)
3650   //----------------------------------
3651   //---<  Print real disassembly  >---
3652   //----------------------------------
3653   if (! use_compressed_format) {
3654     st->print_cr("[Disassembly]");
3655     Disassembler::decode(const_cast<nmethod*>(this), st);
3656     st->bol();
3657     st->print_cr("[/Disassembly]");
3658     return;
3659   }
3660 #endif
3661 
3662 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
3663 
3664   // Compressed undisassembled disassembly format.
3665   // The following status values are defined/supported:
3666   //   = 0 - currently at bol() position, nothing printed yet on current line.
3667   //   = 1 - currently at position after print_location().
3668   //   > 1 - in the midst of printing instruction stream bytes.
3669   int        compressed_format_idx    = 0;
3670   int        code_comment_column      = 0;
3671   const int  instr_maxlen             = Assembler::instr_maxlen();
3672   const uint tabspacing               = 8;
3673   unsigned char* start = this->code_begin();
3674   unsigned char* p     = this->code_begin();
3675   unsigned char* end   = this->code_end();
3676   unsigned char* pss   = p; // start of a code section (used for offsets)
3677 
3678   if ((start == nullptr) || (end == nullptr)) {
3679     st->print_cr("PrintAssembly not possible due to uninitialized section pointers");
3680     return;
3681   }
3682 #endif
3683 
3684 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
3685   //---<  plain abstract disassembly, no comments or anything, just section headers  >---
3686   if (use_compressed_format && ! compressed_with_comments) {
3687     const_cast<nmethod*>(this)->print_constant_pool(st);
3688 
3689     //---<  Open the output (Marker for post-mortem disassembler)  >---
3690     st->print_cr("[MachCode]");
3691     const char* header = nullptr;
3692     address p0 = p;
3693     while (p < end) {
3694       address pp = p;
3695       while ((p < end) && (header == nullptr)) {
3696         header = nmethod_section_label(p);
3697         pp  = p;
3698         p  += Assembler::instr_len(p);
3699       }
3700       if (pp > p0) {
3701         AbstractDisassembler::decode_range_abstract(p0, pp, start, end, st, Assembler::instr_maxlen());
3702         p0 = pp;
3703         p  = pp;
3704         header = nullptr;
3705       } else if (header != nullptr) {
3706         st->bol();
3707         st->print_cr("%s", header);
3708         header = nullptr;
3709       }
3710     }
3711     //---<  Close the output (Marker for post-mortem disassembler)  >---
3712     st->bol();
3713     st->print_cr("[/MachCode]");
3714     return;
3715   }
3716 #endif
3717 
3718 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
3719   //---<  abstract disassembly with comments and section headers merged in  >---
3720   if (compressed_with_comments) {
3721     const_cast<nmethod*>(this)->print_constant_pool(st);
3722 
3723     //---<  Open the output (Marker for post-mortem disassembler)  >---
3724     st->print_cr("[MachCode]");
3725     while ((p < end) && (p != nullptr)) {
3726       const int instruction_size_in_bytes = Assembler::instr_len(p);
3727 
3728       //---<  Block comments for nmethod. Interrupts instruction stream, if any.  >---
3729       // Outputs a bol() before and a cr() after, but only if a comment is printed.
3730       // Prints nmethod_section_label as well.
3731       if (AbstractDisassembler::show_block_comment()) {
3732         print_block_comment(st, p);
3733         if (st->position() == 0) {
3734           compressed_format_idx = 0;
3735         }
3736       }
3737 
3738       //---<  New location information after line break  >---
3739       if (compressed_format_idx == 0) {
3740         code_comment_column   = Disassembler::print_location(p, pss, end, st, false, false);
3741         compressed_format_idx = 1;
3742       }
3743 
3744       //---<  Code comment for current instruction. Address range [p..(p+len))  >---
3745       unsigned char* p_end = p + (ssize_t)instruction_size_in_bytes;
3746       S390_ONLY(if (p_end > end) p_end = end;) // avoid getting past the end
3747 
3748       if (AbstractDisassembler::show_comment() && const_cast<nmethod*>(this)->has_code_comment(p, p_end)) {
3749         //---<  interrupt instruction byte stream for code comment  >---
3750         if (compressed_format_idx > 1) {
3751           st->cr();  // interrupt byte stream
3752           st->cr();  // add an empty line
3753           code_comment_column = Disassembler::print_location(p, pss, end, st, false, false);
3754         }
3755         const_cast<nmethod*>(this)->print_code_comment_on(st, code_comment_column, p, p_end );
3756         st->bol();
3757         compressed_format_idx = 0;
3758       }
3759 
3760       //---<  New location information after line break  >---
3761       if (compressed_format_idx == 0) {
3762         code_comment_column   = Disassembler::print_location(p, pss, end, st, false, false);
3763         compressed_format_idx = 1;
3764       }
3765 
3766       //---<  Nicely align instructions for readability  >---
3767       if (compressed_format_idx > 1) {
3768         Disassembler::print_delimiter(st);
3769       }
3770 
3771       //---<  Now, finally, print the actual instruction bytes  >---
3772       unsigned char* p0 = p;
3773       p = Disassembler::decode_instruction_abstract(p, st, instruction_size_in_bytes, instr_maxlen);
3774       compressed_format_idx += (int)(p - p0);
3775 
3776       if (Disassembler::start_newline(compressed_format_idx-1)) {
3777         st->cr();
3778         compressed_format_idx = 0;
3779       }
3780     }
3781     //---<  Close the output (Marker for post-mortem disassembler)  >---
3782     st->bol();
3783     st->print_cr("[/MachCode]");
3784     return;
3785   }
3786 #endif
3787 }
3788 
3789 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
3790 
3791 const char* nmethod::reloc_string_for(u_char* begin, u_char* end) {
3792   RelocIterator iter(this, begin, end);
3793   bool have_one = false;
3794   while (iter.next()) {
3795     have_one = true;
3796     switch (iter.type()) {
3797         case relocInfo::none: {
3798           // Skip it and check next
3799           break;
3800         }
3801         case relocInfo::oop_type: {
3802           // Get a non-resizable resource-allocated stringStream.
3803           // Our callees make use of (nested) ResourceMarks.
3804           stringStream st(NEW_RESOURCE_ARRAY(char, 1024), 1024);
3805           oop_Relocation* r = iter.oop_reloc();
3806           oop obj = r->oop_value();
3807           st.print("oop(");
3808           if (obj == nullptr) st.print("nullptr");
3809           else obj->print_value_on(&st);
3810           st.print(")");
3811           return st.as_string();
3812         }
3813         case relocInfo::metadata_type: {
3814           stringStream st;
3815           metadata_Relocation* r = iter.metadata_reloc();
3816           Metadata* obj = r->metadata_value();
3817           st.print("metadata(");
3818           if (obj == nullptr) st.print("nullptr");
3819           else obj->print_value_on(&st);
3820           st.print(")");
3821           return st.as_string();
3822         }
3823         case relocInfo::runtime_call_type:
3824         case relocInfo::runtime_call_w_cp_type: {
3825           stringStream st;
3826           st.print("runtime_call");
3827           CallRelocation* r = (CallRelocation*)iter.reloc();
3828           address dest = r->destination();
3829           if (StubRoutines::contains(dest)) {
3830             StubCodeDesc* desc = StubCodeDesc::desc_for(dest);
3831             if (desc == nullptr) {
3832               desc = StubCodeDesc::desc_for(dest + frame::pc_return_offset);
3833             }
3834             if (desc != nullptr) {
3835               st.print(" Stub::%s", desc->name());
3836               return st.as_string();
3837             }
3838           }
3839           CodeBlob* cb = CodeCache::find_blob(dest);
3840           if (cb != nullptr) {
3841             st.print(" %s", cb->name());
3842           } else {
3843             ResourceMark rm;
3844             const int buflen = 1024;
3845             char* buf = NEW_RESOURCE_ARRAY(char, buflen);
3846             int offset;
3847             if (os::dll_address_to_function_name(dest, buf, buflen, &offset)) {
3848               st.print(" %s", buf);
3849               if (offset != 0) {
3850                 st.print("+%d", offset);
3851               }
3852             }
3853           }
3854           return st.as_string();
3855         }
3856         case relocInfo::virtual_call_type: {
3857           stringStream st;
3858           st.print_raw("virtual_call");
3859           virtual_call_Relocation* r = iter.virtual_call_reloc();
3860           Method* m = r->method_value();
3861           if (m != nullptr) {
3862             assert(m->is_method(), "");
3863             m->print_short_name(&st);
3864           }
3865           return st.as_string();
3866         }
3867         case relocInfo::opt_virtual_call_type: {
3868           stringStream st;
3869           st.print_raw("optimized virtual_call");
3870           opt_virtual_call_Relocation* r = iter.opt_virtual_call_reloc();
3871           Method* m = r->method_value();
3872           if (m != nullptr) {
3873             assert(m->is_method(), "");
3874             m->print_short_name(&st);
3875           }
3876           return st.as_string();
3877         }
3878         case relocInfo::static_call_type: {
3879           stringStream st;
3880           st.print_raw("static_call");
3881           static_call_Relocation* r = iter.static_call_reloc();
3882           Method* m = r->method_value();
3883           if (m != nullptr) {
3884             assert(m->is_method(), "");
3885             m->print_short_name(&st);
3886           }
3887           return st.as_string();
3888         }
3889         case relocInfo::static_stub_type:      return "static_stub";
3890         case relocInfo::external_word_type:    return "external_word";
3891         case relocInfo::internal_word_type:    return "internal_word";
3892         case relocInfo::section_word_type:     return "section_word";
3893         case relocInfo::poll_type:             return "poll";
3894         case relocInfo::poll_return_type:      return "poll_return";
3895         case relocInfo::trampoline_stub_type:  return "trampoline_stub";
3896         case relocInfo::entry_guard_type:      return "entry_guard";
3897         case relocInfo::post_call_nop_type:    return "post_call_nop";
3898         case relocInfo::barrier_type: {
3899           barrier_Relocation* const reloc = iter.barrier_reloc();
3900           stringStream st;
3901           st.print("barrier format=%d", reloc->format());
3902           return st.as_string();
3903         }
3904 
3905         case relocInfo::type_mask:             return "type_bit_mask";
3906 
3907         default: {
3908           stringStream st;
3909           st.print("unknown relocInfo=%d", (int) iter.type());
3910           return st.as_string();
3911         }
3912     }
3913   }
3914   return have_one ? "other" : nullptr;
3915 }
3916 
3917 // Return the last scope in (begin..end]
3918 ScopeDesc* nmethod::scope_desc_in(address begin, address end) {
3919   PcDesc* p = pc_desc_near(begin+1);
3920   if (p != nullptr && p->real_pc(this) <= end) {
3921     return new ScopeDesc(this, p);
3922   }
3923   return nullptr;
3924 }
3925 
3926 const char* nmethod::nmethod_section_label(address pos) const {
3927   const char* label = nullptr;
3928   if (pos == code_begin())                                              label = "[Instructions begin]";
3929   if (pos == entry_point())                                             label = "[Entry Point]";
3930   if (pos == verified_entry_point())                                    label = "[Verified Entry Point]";
3931   if (has_method_handle_invokes() && (pos == deopt_mh_handler_begin())) label = "[Deopt MH Handler Code]";
3932   if (pos == consts_begin() && pos != insts_begin())                    label = "[Constants]";
3933   // Check stub_code before checking exception_handler or deopt_handler.
3934   if (pos == this->stub_begin())                                        label = "[Stub Code]";
3935   if (JVMCI_ONLY(_exception_offset >= 0 &&) pos == exception_begin())          label = "[Exception Handler]";
3936   if (JVMCI_ONLY(_deopt_handler_offset != -1 &&) pos == deopt_handler_begin()) label = "[Deopt Handler Code]";
3937   return label;
3938 }
3939 
3940 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin, bool print_section_labels) const {
3941   if (print_section_labels) {
3942     const char* label = nmethod_section_label(block_begin);
3943     if (label != nullptr) {
3944       stream->bol();
3945       stream->print_cr("%s", label);
3946     }
3947   }
3948 
3949   if (block_begin == entry_point()) {
3950     Method* m = method();
3951     if (m != nullptr) {
3952       stream->print("  # ");
3953       m->print_value_on(stream);
3954       stream->cr();
3955     }
3956     if (m != nullptr && !is_osr_method()) {
3957       ResourceMark rm;
3958       int sizeargs = m->size_of_parameters();
3959       BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs);
3960       VMRegPair* regs   = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs);
3961       {
3962         int sig_index = 0;
3963         if (!m->is_static())
3964           sig_bt[sig_index++] = T_OBJECT; // 'this'
3965         for (SignatureStream ss(m->signature()); !ss.at_return_type(); ss.next()) {
3966           BasicType t = ss.type();
3967           sig_bt[sig_index++] = t;
3968           if (type2size[t] == 2) {
3969             sig_bt[sig_index++] = T_VOID;
3970           } else {
3971             assert(type2size[t] == 1, "size is 1 or 2");
3972           }
3973         }
3974         assert(sig_index == sizeargs, "");
3975       }
3976       const char* spname = "sp"; // make arch-specific?
3977       SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs);
3978       int stack_slot_offset = this->frame_size() * wordSize;
3979       int tab1 = 14, tab2 = 24;
3980       int sig_index = 0;
3981       int arg_index = (m->is_static() ? 0 : -1);
3982       bool did_old_sp = false;
3983       for (SignatureStream ss(m->signature()); !ss.at_return_type(); ) {
3984         bool at_this = (arg_index == -1);
3985         bool at_old_sp = false;
3986         BasicType t = (at_this ? T_OBJECT : ss.type());
3987         assert(t == sig_bt[sig_index], "sigs in sync");
3988         if (at_this)
3989           stream->print("  # this: ");
3990         else
3991           stream->print("  # parm%d: ", arg_index);
3992         stream->move_to(tab1);
3993         VMReg fst = regs[sig_index].first();
3994         VMReg snd = regs[sig_index].second();
3995         if (fst->is_reg()) {
3996           stream->print("%s", fst->name());
3997           if (snd->is_valid())  {
3998             stream->print(":%s", snd->name());
3999           }
4000         } else if (fst->is_stack()) {
4001           int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset;
4002           if (offset == stack_slot_offset)  at_old_sp = true;
4003           stream->print("[%s+0x%x]", spname, offset);
4004         } else {
4005           stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd);
4006         }
4007         stream->print(" ");
4008         stream->move_to(tab2);
4009         stream->print("= ");
4010         if (at_this) {
4011           m->method_holder()->print_value_on(stream);
4012         } else {
4013           bool did_name = false;
4014           if (!at_this && ss.is_reference()) {
4015             Symbol* name = ss.as_symbol();
4016             name->print_value_on(stream);
4017             did_name = true;
4018           }
4019           if (!did_name)
4020             stream->print("%s", type2name(t));
4021         }
4022         if (at_old_sp) {
4023           stream->print("  (%s of caller)", spname);
4024           did_old_sp = true;
4025         }
4026         stream->cr();
4027         sig_index += type2size[t];
4028         arg_index += 1;
4029         if (!at_this)  ss.next();
4030       }
4031       if (!did_old_sp) {
4032         stream->print("  # ");
4033         stream->move_to(tab1);
4034         stream->print("[%s+0x%x]", spname, stack_slot_offset);
4035         stream->print("  (%s of caller)", spname);
4036         stream->cr();
4037       }
4038     }
4039   }
4040 }
4041 
4042 // Returns whether this nmethod has code comments.
4043 bool nmethod::has_code_comment(address begin, address end) {
4044   // scopes?
4045   ScopeDesc* sd  = scope_desc_in(begin, end);
4046   if (sd != nullptr) return true;
4047 
4048   // relocations?
4049   const char* str = reloc_string_for(begin, end);
4050   if (str != nullptr) return true;
4051 
4052   // implicit exceptions?
4053   int cont_offset = ImplicitExceptionTable(this).continuation_offset((uint)(begin - code_begin()));
4054   if (cont_offset != 0) return true;
4055 
4056   return false;
4057 }
4058 
4059 void nmethod::print_code_comment_on(outputStream* st, int column, address begin, address end) {
4060   ImplicitExceptionTable implicit_table(this);
4061   int pc_offset = (int)(begin - code_begin());
4062   int cont_offset = implicit_table.continuation_offset(pc_offset);
4063   bool oop_map_required = false;
4064   if (cont_offset != 0) {
4065     st->move_to(column, 6, 0);
4066     if (pc_offset == cont_offset) {
4067       st->print("; implicit exception: deoptimizes");
4068       oop_map_required = true;
4069     } else {
4070       st->print("; implicit exception: dispatches to " INTPTR_FORMAT, p2i(code_begin() + cont_offset));
4071     }
4072   }
4073 
4074   // Find an oopmap in (begin, end].  We use the odd half-closed
4075   // interval so that oop maps and scope descs which are tied to the
4076   // byte after a call are printed with the call itself.  OopMaps
4077   // associated with implicit exceptions are printed with the implicit
4078   // instruction.
4079   address base = code_begin();
4080   ImmutableOopMapSet* oms = oop_maps();
4081   if (oms != nullptr) {
4082     for (int i = 0, imax = oms->count(); i < imax; i++) {
4083       const ImmutableOopMapPair* pair = oms->pair_at(i);
4084       const ImmutableOopMap* om = pair->get_from(oms);
4085       address pc = base + pair->pc_offset();
4086       if (pc >= begin) {
4087 #if INCLUDE_JVMCI
4088         bool is_implicit_deopt = implicit_table.continuation_offset(pair->pc_offset()) == (uint) pair->pc_offset();
4089 #else
4090         bool is_implicit_deopt = false;
4091 #endif
4092         if (is_implicit_deopt ? pc == begin : pc > begin && pc <= end) {
4093           st->move_to(column, 6, 0);
4094           st->print("; ");
4095           om->print_on(st);
4096           oop_map_required = false;
4097         }
4098       }
4099       if (pc > end) {
4100         break;
4101       }
4102     }
4103   }
4104   assert(!oop_map_required, "missed oopmap");
4105 
4106   Thread* thread = Thread::current();
4107 
4108   // Print any debug info present at this pc.
4109   ScopeDesc* sd  = scope_desc_in(begin, end);
4110   if (sd != nullptr) {
4111     st->move_to(column, 6, 0);
4112     if (sd->bci() == SynchronizationEntryBCI) {
4113       st->print(";*synchronization entry");
4114     } else if (sd->bci() == AfterBci) {
4115       st->print(";* method exit (unlocked if synchronized)");
4116     } else if (sd->bci() == UnwindBci) {
4117       st->print(";* unwind (locked if synchronized)");
4118     } else if (sd->bci() == AfterExceptionBci) {
4119       st->print(";* unwind (unlocked if synchronized)");
4120     } else if (sd->bci() == UnknownBci) {
4121       st->print(";* unknown");
4122     } else if (sd->bci() == InvalidFrameStateBci) {
4123       st->print(";* invalid frame state");
4124     } else {
4125       if (sd->method() == nullptr) {
4126         st->print("method is nullptr");
4127       } else if (sd->method()->is_native()) {
4128         st->print("method is native");
4129       } else {
4130         Bytecodes::Code bc = sd->method()->java_code_at(sd->bci());
4131         st->print(";*%s", Bytecodes::name(bc));
4132         switch (bc) {
4133         case Bytecodes::_invokevirtual:
4134         case Bytecodes::_invokespecial:
4135         case Bytecodes::_invokestatic:
4136         case Bytecodes::_invokeinterface:
4137           {
4138             Bytecode_invoke invoke(methodHandle(thread, sd->method()), sd->bci());
4139             st->print(" ");
4140             if (invoke.name() != nullptr)
4141               invoke.name()->print_symbol_on(st);
4142             else
4143               st->print("<UNKNOWN>");
4144             break;
4145           }
4146         case Bytecodes::_getfield:
4147         case Bytecodes::_putfield:
4148         case Bytecodes::_getstatic:
4149         case Bytecodes::_putstatic:
4150           {
4151             Bytecode_field field(methodHandle(thread, sd->method()), sd->bci());
4152             st->print(" ");
4153             if (field.name() != nullptr)
4154               field.name()->print_symbol_on(st);
4155             else
4156               st->print("<UNKNOWN>");
4157           }
4158         default:
4159           break;
4160         }
4161       }
4162       st->print(" {reexecute=%d rethrow=%d return_oop=%d}", sd->should_reexecute(), sd->rethrow_exception(), sd->return_oop());
4163     }
4164 
4165     // Print all scopes
4166     for (;sd != nullptr; sd = sd->sender()) {
4167       st->move_to(column, 6, 0);
4168       st->print("; -");
4169       if (sd->should_reexecute()) {
4170         st->print(" (reexecute)");
4171       }
4172       if (sd->method() == nullptr) {
4173         st->print("method is nullptr");
4174       } else {
4175         sd->method()->print_short_name(st);
4176       }
4177       int lineno = sd->method()->line_number_from_bci(sd->bci());
4178       if (lineno != -1) {
4179         st->print("@%d (line %d)", sd->bci(), lineno);
4180       } else {
4181         st->print("@%d", sd->bci());
4182       }
4183       st->cr();
4184     }
4185   }
4186 
4187   // Print relocation information
4188   // Prevent memory leak: allocating without ResourceMark.
4189   ResourceMark rm;
4190   const char* str = reloc_string_for(begin, end);
4191   if (str != nullptr) {
4192     if (sd != nullptr) st->cr();
4193     st->move_to(column, 6, 0);
4194     st->print(";   {%s}", str);
4195   }
4196 }
4197 
4198 #endif
4199 
4200 address nmethod::call_instruction_address(address pc) const {
4201   if (NativeCall::is_call_before(pc)) {
4202     NativeCall *ncall = nativeCall_before(pc);
4203     return ncall->instruction_address();
4204   }
4205   return nullptr;
4206 }
4207 
4208 void nmethod::print_value_on_impl(outputStream* st) const {
4209   st->print_cr("nmethod");
4210 #if defined(SUPPORT_DATA_STRUCTS)
4211   print_on_with_msg(st, nullptr);
4212 #endif
4213 }
4214 
4215 #ifndef PRODUCT
4216 
4217 void nmethod::print_calls(outputStream* st) {
4218   RelocIterator iter(this);
4219   while (iter.next()) {
4220     switch (iter.type()) {
4221     case relocInfo::virtual_call_type: {
4222       CompiledICLocker ml_verify(this);
4223       CompiledIC_at(&iter)->print();
4224       break;
4225     }
4226     case relocInfo::static_call_type:
4227     case relocInfo::opt_virtual_call_type:
4228       st->print_cr("Direct call at " INTPTR_FORMAT, p2i(iter.reloc()->addr()));
4229       CompiledDirectCall::at(iter.reloc())->print();
4230       break;
4231     default:
4232       break;
4233     }
4234   }
4235 }
4236 
4237 void nmethod::print_statistics() {
4238   ttyLocker ttyl;
4239   if (xtty != nullptr)  xtty->head("statistics type='nmethod'");
4240   native_nmethod_stats.print_native_nmethod_stats();
4241 #ifdef COMPILER1
4242   c1_java_nmethod_stats.print_nmethod_stats("C1");
4243 #endif
4244 #ifdef COMPILER2
4245   c2_java_nmethod_stats.print_nmethod_stats("C2");
4246 #endif
4247 #if INCLUDE_JVMCI
4248   jvmci_java_nmethod_stats.print_nmethod_stats("JVMCI");
4249 #endif
4250   unknown_java_nmethod_stats.print_nmethod_stats("Unknown");
4251   DebugInformationRecorder::print_statistics();
4252   pc_nmethod_stats.print_pc_stats();
4253   Dependencies::print_statistics();
4254   ExternalsRecorder::print_statistics();
4255   if (xtty != nullptr)  xtty->tail("statistics");
4256 }
4257 
4258 #endif // !PRODUCT
4259 
4260 #if INCLUDE_JVMCI
4261 void nmethod::update_speculation(JavaThread* thread) {
4262   jlong speculation = thread->pending_failed_speculation();
4263   if (speculation != 0) {
4264     guarantee(jvmci_nmethod_data() != nullptr, "failed speculation in nmethod without failed speculation list");
4265     jvmci_nmethod_data()->add_failed_speculation(this, speculation);
4266     thread->set_pending_failed_speculation(0);
4267   }
4268 }
4269 
4270 const char* nmethod::jvmci_name() {
4271   if (jvmci_nmethod_data() != nullptr) {
4272     return jvmci_nmethod_data()->name();
4273   }
4274   return nullptr;
4275 }
4276 #endif
4277 
4278 void nmethod::prepare_for_archiving() {
4279   CodeBlob::prepare_for_archiving();
4280   _deoptimization_generation = 0;
4281   _gc_epoch = 0;
4282   _method_profiling_count = 0;
4283   _osr_link = nullptr;
4284   _method = nullptr;
4285   _immutable_data = nullptr;
4286   _pc_desc_container = nullptr;
4287   _exception_cache = nullptr;
4288   _gc_data = nullptr;
4289   _oops_do_mark_link = nullptr;
4290   _compiled_ic_data = nullptr;
4291   _osr_entry_point = nullptr;
4292   _compile_id = -1;
4293   _deoptimization_status = not_marked;
4294   _is_unloading_state = 0;
4295   _state = not_installed;
4296 }