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