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