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