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