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