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