1 /*
   2  * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "asm/assembler.inline.hpp"
  26 #include "code/codeCache.hpp"
  27 #include "code/compiledIC.hpp"
  28 #include "code/dependencies.hpp"
  29 #include "code/nativeInst.hpp"
  30 #include "code/nmethod.inline.hpp"
  31 #include "code/scopeDesc.hpp"
  32 #include "compiler/abstractCompiler.hpp"
  33 #include "compiler/compilationLog.hpp"
  34 #include "compiler/compileBroker.hpp"
  35 #include "compiler/compileLog.hpp"
  36 #include "compiler/compilerDirectives.hpp"
  37 #include "compiler/compilerOracle.hpp"
  38 #include "compiler/compileTask.hpp"
  39 #include "compiler/directivesParser.hpp"
  40 #include "compiler/disassembler.hpp"
  41 #include "compiler/oopMap.inline.hpp"
  42 #include "gc/shared/barrierSet.hpp"
  43 #include "gc/shared/barrierSetNMethod.hpp"
  44 #include "gc/shared/classUnloadingContext.hpp"
  45 #include "gc/shared/collectedHeap.hpp"
  46 #include "interpreter/bytecode.inline.hpp"
  47 #include "jvm.h"
  48 #include "logging/log.hpp"
  49 #include "logging/logStream.hpp"
  50 #include "memory/allocation.inline.hpp"
  51 #include "memory/resourceArea.hpp"
  52 #include "memory/universe.hpp"
  53 #include "oops/access.inline.hpp"
  54 #include "oops/klass.inline.hpp"
  55 #include "oops/method.inline.hpp"
  56 #include "oops/methodData.hpp"
  57 #include "oops/oop.inline.hpp"
  58 #include "oops/weakHandle.inline.hpp"
  59 #include "prims/jvmtiImpl.hpp"
  60 #include "prims/jvmtiThreadState.hpp"
  61 #include "prims/methodHandles.hpp"
  62 #include "runtime/atomic.hpp"
  63 #include "runtime/continuation.hpp"
  64 #include "runtime/deoptimization.hpp"
  65 #include "runtime/flags/flagSetting.hpp"
  66 #include "runtime/frame.inline.hpp"
  67 #include "runtime/handles.inline.hpp"
  68 #include "runtime/jniHandles.inline.hpp"
  69 #include "runtime/orderAccess.hpp"
  70 #include "runtime/os.hpp"
  71 #include "runtime/safepointVerifiers.hpp"
  72 #include "runtime/serviceThread.hpp"
  73 #include "runtime/sharedRuntime.hpp"
  74 #include "runtime/signature.hpp"
  75 #include "runtime/threadWXSetters.inline.hpp"
  76 #include "runtime/vmThread.hpp"
  77 #include "utilities/align.hpp"
  78 #include "utilities/copy.hpp"
  79 #include "utilities/dtrace.hpp"
  80 #include "utilities/events.hpp"
  81 #include "utilities/globalDefinitions.hpp"
  82 #include "utilities/hashTable.hpp"
  83 #include "utilities/xmlstream.hpp"
  84 #if INCLUDE_JVMCI
  85 #include "jvmci/jvmciRuntime.hpp"
  86 #endif
  87 
  88 #ifdef DTRACE_ENABLED
  89 
  90 // Only bother with this argument setup if dtrace is available
  91 
  92 #define DTRACE_METHOD_UNLOAD_PROBE(method)                                \
  93   {                                                                       \
  94     Method* m = (method);                                                 \
  95     if (m != nullptr) {                                                   \
  96       Symbol* klass_name = m->klass_name();                               \
  97       Symbol* name = m->name();                                           \
  98       Symbol* signature = m->signature();                                 \
  99       HOTSPOT_COMPILED_METHOD_UNLOAD(                                     \
 100         (char *) klass_name->bytes(), klass_name->utf8_length(),          \
 101         (char *) name->bytes(), name->utf8_length(),                      \
 102         (char *) signature->bytes(), signature->utf8_length());           \
 103     }                                                                     \
 104   }
 105 
 106 #else //  ndef DTRACE_ENABLED
 107 
 108 #define DTRACE_METHOD_UNLOAD_PROBE(method)
 109 
 110 #endif
 111 
 112 // Cast from int value to narrow type
 113 #define CHECKED_CAST(result, T, thing)      \
 114   result = static_cast<T>(thing); \
 115   guarantee(static_cast<int>(result) == thing, "failed: %d != %d", static_cast<int>(result), thing);
 116 
 117 //---------------------------------------------------------------------------------
 118 // NMethod statistics
 119 // They are printed under various flags, including:
 120 //   PrintC1Statistics, PrintOptoStatistics, LogVMOutput, and LogCompilation.
 121 // (In the latter two cases, they like other stats are printed to the log only.)
 122 
 123 #ifndef PRODUCT
 124 // These variables are put into one block to reduce relocations
 125 // and make it simpler to print from the debugger.
 126 struct java_nmethod_stats_struct {
 127   uint nmethod_count;
 128   uint total_nm_size;
 129   uint total_immut_size;
 130   uint total_mut_size;
 131   uint relocation_size;
 132   uint consts_size;
 133   uint insts_size;
 134   uint stub_size;
 135   uint oops_size;
 136   uint metadata_size;
 137   uint dependencies_size;
 138   uint nul_chk_table_size;
 139   uint handler_table_size;
 140   uint scopes_pcs_size;
 141   uint scopes_data_size;
 142 #if INCLUDE_JVMCI
 143   uint speculations_size;
 144   uint jvmci_data_size;
 145 #endif
 146 
 147   void note_nmethod(nmethod* nm) {
 148     nmethod_count += 1;
 149     total_nm_size       += nm->size();
 150     total_immut_size    += nm->immutable_data_size();
 151     total_mut_size      += nm->mutable_data_size();
 152     relocation_size     += nm->relocation_size();
 153     consts_size         += nm->consts_size();
 154     insts_size          += nm->insts_size();
 155     stub_size           += nm->stub_size();
 156     oops_size           += nm->oops_size();
 157     metadata_size       += nm->metadata_size();
 158     scopes_data_size    += nm->scopes_data_size();
 159     scopes_pcs_size     += nm->scopes_pcs_size();
 160     dependencies_size   += nm->dependencies_size();
 161     handler_table_size  += nm->handler_table_size();
 162     nul_chk_table_size  += nm->nul_chk_table_size();
 163 #if INCLUDE_JVMCI
 164     speculations_size   += nm->speculations_size();
 165     jvmci_data_size     += nm->jvmci_data_size();
 166 #endif
 167   }
 168   void print_nmethod_stats(const char* name) {
 169     if (nmethod_count == 0)  return;
 170     tty->print_cr("Statistics for %u bytecoded nmethods for %s:", nmethod_count, name);
 171     uint total_size = total_nm_size + total_immut_size + total_mut_size;
 172     if (total_nm_size != 0) {
 173       tty->print_cr(" total size      = %u (100%%)", total_size);
 174       tty->print_cr(" in CodeCache    = %u (%f%%)", total_nm_size, (total_nm_size * 100.0f)/total_size);
 175     }
 176     uint header_size = (uint)(nmethod_count * sizeof(nmethod));
 177     if (nmethod_count != 0) {
 178       tty->print_cr("   header        = %u (%f%%)", header_size, (header_size * 100.0f)/total_nm_size);
 179     }
 180     if (consts_size != 0) {
 181       tty->print_cr("   constants     = %u (%f%%)", consts_size, (consts_size * 100.0f)/total_nm_size);
 182     }
 183     if (insts_size != 0) {
 184       tty->print_cr("   main code     = %u (%f%%)", insts_size, (insts_size * 100.0f)/total_nm_size);
 185     }
 186     if (stub_size != 0) {
 187       tty->print_cr("   stub code     = %u (%f%%)", stub_size, (stub_size * 100.0f)/total_nm_size);
 188     }
 189     if (oops_size != 0) {
 190       tty->print_cr("   oops          = %u (%f%%)", oops_size, (oops_size * 100.0f)/total_nm_size);
 191     }
 192     if (total_mut_size != 0) {
 193       tty->print_cr(" mutable data    = %u (%f%%)", total_mut_size, (total_mut_size * 100.0f)/total_size);
 194     }
 195     if (relocation_size != 0) {
 196       tty->print_cr("   relocation    = %u (%f%%)", relocation_size, (relocation_size * 100.0f)/total_mut_size);
 197     }
 198     if (metadata_size != 0) {
 199       tty->print_cr("   metadata      = %u (%f%%)", metadata_size, (metadata_size * 100.0f)/total_mut_size);
 200     }
 201 #if INCLUDE_JVMCI
 202     if (jvmci_data_size != 0) {
 203       tty->print_cr("   JVMCI data    = %u (%f%%)", jvmci_data_size, (jvmci_data_size * 100.0f)/total_mut_size);
 204     }
 205 #endif
 206     if (total_immut_size != 0) {
 207       tty->print_cr(" immutable data  = %u (%f%%)", total_immut_size, (total_immut_size * 100.0f)/total_size);
 208     }
 209     if (dependencies_size != 0) {
 210       tty->print_cr("   dependencies  = %u (%f%%)", dependencies_size, (dependencies_size * 100.0f)/total_immut_size);
 211     }
 212     if (nul_chk_table_size != 0) {
 213       tty->print_cr("   nul chk table = %u (%f%%)", nul_chk_table_size, (nul_chk_table_size * 100.0f)/total_immut_size);
 214     }
 215     if (handler_table_size != 0) {
 216       tty->print_cr("   handler table = %u (%f%%)", handler_table_size, (handler_table_size * 100.0f)/total_immut_size);
 217     }
 218     if (scopes_pcs_size != 0) {
 219       tty->print_cr("   scopes pcs    = %u (%f%%)", scopes_pcs_size, (scopes_pcs_size * 100.0f)/total_immut_size);
 220     }
 221     if (scopes_data_size != 0) {
 222       tty->print_cr("   scopes data   = %u (%f%%)", scopes_data_size, (scopes_data_size * 100.0f)/total_immut_size);
 223     }
 224 #if INCLUDE_JVMCI
 225     if (speculations_size != 0) {
 226       tty->print_cr("   speculations  = %u (%f%%)", speculations_size, (speculations_size * 100.0f)/total_immut_size);
 227     }
 228 #endif
 229   }
 230 };
 231 
 232 struct native_nmethod_stats_struct {
 233   uint native_nmethod_count;
 234   uint native_total_size;
 235   uint native_relocation_size;
 236   uint native_insts_size;
 237   uint native_oops_size;
 238   uint native_metadata_size;
 239   void note_native_nmethod(nmethod* nm) {
 240     native_nmethod_count += 1;
 241     native_total_size       += nm->size();
 242     native_relocation_size  += nm->relocation_size();
 243     native_insts_size       += nm->insts_size();
 244     native_oops_size        += nm->oops_size();
 245     native_metadata_size    += nm->metadata_size();
 246   }
 247   void print_native_nmethod_stats() {
 248     if (native_nmethod_count == 0)  return;
 249     tty->print_cr("Statistics for %u native nmethods:", native_nmethod_count);
 250     if (native_total_size != 0)       tty->print_cr(" N. total size  = %u", native_total_size);
 251     if (native_relocation_size != 0)  tty->print_cr(" N. relocation  = %u", native_relocation_size);
 252     if (native_insts_size != 0)       tty->print_cr(" N. main code   = %u", native_insts_size);
 253     if (native_oops_size != 0)        tty->print_cr(" N. oops        = %u", native_oops_size);
 254     if (native_metadata_size != 0)    tty->print_cr(" N. metadata    = %u", native_metadata_size);
 255   }
 256 };
 257 
 258 struct pc_nmethod_stats_struct {
 259   uint pc_desc_init;     // number of initialization of cache (= number of caches)
 260   uint pc_desc_queries;  // queries to nmethod::find_pc_desc
 261   uint pc_desc_approx;   // number of those which have approximate true
 262   uint pc_desc_repeats;  // number of _pc_descs[0] hits
 263   uint pc_desc_hits;     // number of LRU cache hits
 264   uint pc_desc_tests;    // total number of PcDesc examinations
 265   uint pc_desc_searches; // total number of quasi-binary search steps
 266   uint pc_desc_adds;     // number of LUR cache insertions
 267 
 268   void print_pc_stats() {
 269     tty->print_cr("PcDesc Statistics:  %u queries, %.2f comparisons per query",
 270                   pc_desc_queries,
 271                   (double)(pc_desc_tests + pc_desc_searches)
 272                   / pc_desc_queries);
 273     tty->print_cr("  caches=%d queries=%u/%u, hits=%u+%u, tests=%u+%u, adds=%u",
 274                   pc_desc_init,
 275                   pc_desc_queries, pc_desc_approx,
 276                   pc_desc_repeats, pc_desc_hits,
 277                   pc_desc_tests, pc_desc_searches, pc_desc_adds);
 278   }
 279 };
 280 
 281 #ifdef COMPILER1
 282 static java_nmethod_stats_struct c1_java_nmethod_stats;
 283 #endif
 284 #ifdef COMPILER2
 285 static java_nmethod_stats_struct c2_java_nmethod_stats;
 286 #endif
 287 #if INCLUDE_JVMCI
 288 static java_nmethod_stats_struct jvmci_java_nmethod_stats;
 289 #endif
 290 static java_nmethod_stats_struct unknown_java_nmethod_stats;
 291 
 292 static native_nmethod_stats_struct native_nmethod_stats;
 293 static pc_nmethod_stats_struct pc_nmethod_stats;
 294 
 295 static void note_java_nmethod(nmethod* nm) {
 296 #ifdef COMPILER1
 297   if (nm->is_compiled_by_c1()) {
 298     c1_java_nmethod_stats.note_nmethod(nm);
 299   } else
 300 #endif
 301 #ifdef COMPILER2
 302   if (nm->is_compiled_by_c2()) {
 303     c2_java_nmethod_stats.note_nmethod(nm);
 304   } else
 305 #endif
 306 #if INCLUDE_JVMCI
 307   if (nm->is_compiled_by_jvmci()) {
 308     jvmci_java_nmethod_stats.note_nmethod(nm);
 309   } else
 310 #endif
 311   {
 312     unknown_java_nmethod_stats.note_nmethod(nm);
 313   }
 314 }
 315 #endif // !PRODUCT
 316 
 317 //---------------------------------------------------------------------------------
 318 
 319 
 320 ExceptionCache::ExceptionCache(Handle exception, address pc, address handler) {
 321   assert(pc != nullptr, "Must be non null");
 322   assert(exception.not_null(), "Must be non null");
 323   assert(handler != nullptr, "Must be non null");
 324 
 325   _count = 0;
 326   _exception_type = exception->klass();
 327   _next = nullptr;
 328   _purge_list_next = nullptr;
 329 
 330   add_address_and_handler(pc,handler);
 331 }
 332 
 333 
 334 address ExceptionCache::match(Handle exception, address pc) {
 335   assert(pc != nullptr,"Must be non null");
 336   assert(exception.not_null(),"Must be non null");
 337   if (exception->klass() == exception_type()) {
 338     return (test_address(pc));
 339   }
 340 
 341   return nullptr;
 342 }
 343 
 344 
 345 bool ExceptionCache::match_exception_with_space(Handle exception) {
 346   assert(exception.not_null(),"Must be non null");
 347   if (exception->klass() == exception_type() && count() < cache_size) {
 348     return true;
 349   }
 350   return false;
 351 }
 352 
 353 
 354 address ExceptionCache::test_address(address addr) {
 355   int limit = count();
 356   for (int i = 0; i < limit; i++) {
 357     if (pc_at(i) == addr) {
 358       return handler_at(i);
 359     }
 360   }
 361   return nullptr;
 362 }
 363 
 364 
 365 bool ExceptionCache::add_address_and_handler(address addr, address handler) {
 366   if (test_address(addr) == handler) return true;
 367 
 368   int index = count();
 369   if (index < cache_size) {
 370     set_pc_at(index, addr);
 371     set_handler_at(index, handler);
 372     increment_count();
 373     return true;
 374   }
 375   return false;
 376 }
 377 
 378 ExceptionCache* ExceptionCache::next() {
 379   return Atomic::load(&_next);
 380 }
 381 
 382 void ExceptionCache::set_next(ExceptionCache *ec) {
 383   Atomic::store(&_next, ec);
 384 }
 385 
 386 //-----------------------------------------------------------------------------
 387 
 388 
 389 // Helper used by both find_pc_desc methods.
 390 static inline bool match_desc(PcDesc* pc, int pc_offset, bool approximate) {
 391   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_tests);
 392   if (!approximate) {
 393     return pc->pc_offset() == pc_offset;
 394   } else {
 395     // Do not look before the sentinel
 396     assert(pc_offset > PcDesc::lower_offset_limit, "illegal pc_offset");
 397     return pc_offset <= pc->pc_offset() && (pc-1)->pc_offset() < pc_offset;
 398   }
 399 }
 400 
 401 void PcDescCache::init_to(PcDesc* initial_pc_desc) {
 402   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_init);
 403   // initialize the cache by filling it with benign (non-null) values
 404   assert(initial_pc_desc != nullptr && initial_pc_desc->pc_offset() == PcDesc::lower_offset_limit,
 405          "must start with a sentinel");
 406   for (int i = 0; i < cache_size; i++) {
 407     _pc_descs[i] = initial_pc_desc;
 408   }
 409 }
 410 
 411 PcDesc* PcDescCache::find_pc_desc(int pc_offset, bool approximate) {
 412   // Note: one might think that caching the most recently
 413   // read value separately would be a win, but one would be
 414   // wrong.  When many threads are updating it, the cache
 415   // line it's in would bounce between caches, negating
 416   // any benefit.
 417 
 418   // In order to prevent race conditions do not load cache elements
 419   // repeatedly, but use a local copy:
 420   PcDesc* res;
 421 
 422   // Step one:  Check the most recently added value.
 423   res = _pc_descs[0];
 424   assert(res != nullptr, "PcDesc cache should be initialized already");
 425 
 426   // Approximate only here since PcDescContainer::find_pc_desc() checked for exact case.
 427   if (approximate && match_desc(res, pc_offset, approximate)) {
 428     NOT_PRODUCT(++pc_nmethod_stats.pc_desc_repeats);
 429     return res;
 430   }
 431 
 432   // Step two:  Check the rest of the LRU cache.
 433   for (int i = 1; i < cache_size; ++i) {
 434     res = _pc_descs[i];
 435     if (res->pc_offset() < 0) break;  // optimization: skip empty cache
 436     if (match_desc(res, pc_offset, approximate)) {
 437       NOT_PRODUCT(++pc_nmethod_stats.pc_desc_hits);
 438       return res;
 439     }
 440   }
 441 
 442   // Report failure.
 443   return nullptr;
 444 }
 445 
 446 void PcDescCache::add_pc_desc(PcDesc* pc_desc) {
 447   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_adds);
 448   // Update the LRU cache by shifting pc_desc forward.
 449   for (int i = 0; i < cache_size; i++)  {
 450     PcDesc* next = _pc_descs[i];
 451     _pc_descs[i] = pc_desc;
 452     pc_desc = next;
 453   }
 454 }
 455 
 456 // adjust pcs_size so that it is a multiple of both oopSize and
 457 // sizeof(PcDesc) (assumes that if sizeof(PcDesc) is not a multiple
 458 // of oopSize, then 2*sizeof(PcDesc) is)
 459 static int adjust_pcs_size(int pcs_size) {
 460   int nsize = align_up(pcs_size,   oopSize);
 461   if ((nsize % sizeof(PcDesc)) != 0) {
 462     nsize = pcs_size + sizeof(PcDesc);
 463   }
 464   assert((nsize % oopSize) == 0, "correct alignment");
 465   return nsize;
 466 }
 467 
 468 bool nmethod::is_method_handle_return(address return_pc) {
 469   if (!has_method_handle_invokes())  return false;
 470   PcDesc* pd = pc_desc_at(return_pc);
 471   if (pd == nullptr)
 472     return false;
 473   return pd->is_method_handle_invoke();
 474 }
 475 
 476 // Returns a string version of the method state.
 477 const char* nmethod::state() const {
 478   int state = get_state();
 479   switch (state) {
 480   case not_installed:
 481     return "not installed";
 482   case in_use:
 483     return "in use";
 484   case not_entrant:
 485     return "not_entrant";
 486   default:
 487     fatal("unexpected method state: %d", state);
 488     return nullptr;
 489   }
 490 }
 491 
 492 void nmethod::set_deoptimized_done() {
 493   ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
 494   if (_deoptimization_status != deoptimize_done) { // can't go backwards
 495     Atomic::store(&_deoptimization_status, deoptimize_done);
 496   }
 497 }
 498 
 499 ExceptionCache* nmethod::exception_cache_acquire() const {
 500   return Atomic::load_acquire(&_exception_cache);
 501 }
 502 
 503 void nmethod::add_exception_cache_entry(ExceptionCache* new_entry) {
 504   assert(ExceptionCache_lock->owned_by_self(),"Must hold the ExceptionCache_lock");
 505   assert(new_entry != nullptr,"Must be non null");
 506   assert(new_entry->next() == nullptr, "Must be null");
 507 
 508   for (;;) {
 509     ExceptionCache *ec = exception_cache();
 510     if (ec != nullptr) {
 511       Klass* ex_klass = ec->exception_type();
 512       if (!ex_klass->is_loader_alive()) {
 513         // We must guarantee that entries are not inserted with new next pointer
 514         // edges to ExceptionCache entries with dead klasses, due to bad interactions
 515         // with concurrent ExceptionCache cleanup. Therefore, the inserts roll
 516         // the head pointer forward to the first live ExceptionCache, so that the new
 517         // next pointers always point at live ExceptionCaches, that are not removed due
 518         // to concurrent ExceptionCache cleanup.
 519         ExceptionCache* next = ec->next();
 520         if (Atomic::cmpxchg(&_exception_cache, ec, next) == ec) {
 521           CodeCache::release_exception_cache(ec);
 522         }
 523         continue;
 524       }
 525       ec = exception_cache();
 526       if (ec != nullptr) {
 527         new_entry->set_next(ec);
 528       }
 529     }
 530     if (Atomic::cmpxchg(&_exception_cache, ec, new_entry) == ec) {
 531       return;
 532     }
 533   }
 534 }
 535 
 536 void nmethod::clean_exception_cache() {
 537   // For each nmethod, only a single thread may call this cleanup function
 538   // at the same time, whether called in STW cleanup or concurrent cleanup.
 539   // Note that if the GC is processing exception cache cleaning in a concurrent phase,
 540   // then a single writer may contend with cleaning up the head pointer to the
 541   // first ExceptionCache node that has a Klass* that is alive. That is fine,
 542   // as long as there is no concurrent cleanup of next pointers from concurrent writers.
 543   // And the concurrent writers do not clean up next pointers, only the head.
 544   // Also note that concurrent readers will walk through Klass* pointers that are not
 545   // alive. That does not cause ABA problems, because Klass* is deleted after
 546   // a handshake with all threads, after all stale ExceptionCaches have been
 547   // unlinked. That is also when the CodeCache::exception_cache_purge_list()
 548   // is deleted, with all ExceptionCache entries that were cleaned concurrently.
 549   // That similarly implies that CAS operations on ExceptionCache entries do not
 550   // suffer from ABA problems as unlinking and deletion is separated by a global
 551   // handshake operation.
 552   ExceptionCache* prev = nullptr;
 553   ExceptionCache* curr = exception_cache_acquire();
 554 
 555   while (curr != nullptr) {
 556     ExceptionCache* next = curr->next();
 557 
 558     if (!curr->exception_type()->is_loader_alive()) {
 559       if (prev == nullptr) {
 560         // Try to clean head; this is contended by concurrent inserts, that
 561         // both lazily clean the head, and insert entries at the head. If
 562         // the CAS fails, the operation is restarted.
 563         if (Atomic::cmpxchg(&_exception_cache, curr, next) != curr) {
 564           prev = nullptr;
 565           curr = exception_cache_acquire();
 566           continue;
 567         }
 568       } else {
 569         // It is impossible to during cleanup connect the next pointer to
 570         // an ExceptionCache that has not been published before a safepoint
 571         // prior to the cleanup. Therefore, release is not required.
 572         prev->set_next(next);
 573       }
 574       // prev stays the same.
 575 
 576       CodeCache::release_exception_cache(curr);
 577     } else {
 578       prev = curr;
 579     }
 580 
 581     curr = next;
 582   }
 583 }
 584 
 585 // public method for accessing the exception cache
 586 // These are the public access methods.
 587 address nmethod::handler_for_exception_and_pc(Handle exception, address pc) {
 588   // We never grab a lock to read the exception cache, so we may
 589   // have false negatives. This is okay, as it can only happen during
 590   // the first few exception lookups for a given nmethod.
 591   ExceptionCache* ec = exception_cache_acquire();
 592   while (ec != nullptr) {
 593     address ret_val;
 594     if ((ret_val = ec->match(exception,pc)) != nullptr) {
 595       return ret_val;
 596     }
 597     ec = ec->next();
 598   }
 599   return nullptr;
 600 }
 601 
 602 void nmethod::add_handler_for_exception_and_pc(Handle exception, address pc, address handler) {
 603   // There are potential race conditions during exception cache updates, so we
 604   // must own the ExceptionCache_lock before doing ANY modifications. Because
 605   // we don't lock during reads, it is possible to have several threads attempt
 606   // to update the cache with the same data. We need to check for already inserted
 607   // copies of the current data before adding it.
 608 
 609   MutexLocker ml(ExceptionCache_lock);
 610   ExceptionCache* target_entry = exception_cache_entry_for_exception(exception);
 611 
 612   if (target_entry == nullptr || !target_entry->add_address_and_handler(pc,handler)) {
 613     target_entry = new ExceptionCache(exception,pc,handler);
 614     add_exception_cache_entry(target_entry);
 615   }
 616 }
 617 
 618 // private method for handling exception cache
 619 // These methods are private, and used to manipulate the exception cache
 620 // directly.
 621 ExceptionCache* nmethod::exception_cache_entry_for_exception(Handle exception) {
 622   ExceptionCache* ec = exception_cache_acquire();
 623   while (ec != nullptr) {
 624     if (ec->match_exception_with_space(exception)) {
 625       return ec;
 626     }
 627     ec = ec->next();
 628   }
 629   return nullptr;
 630 }
 631 
 632 bool nmethod::is_at_poll_return(address pc) {
 633   RelocIterator iter(this, pc, pc+1);
 634   while (iter.next()) {
 635     if (iter.type() == relocInfo::poll_return_type)
 636       return true;
 637   }
 638   return false;
 639 }
 640 
 641 
 642 bool nmethod::is_at_poll_or_poll_return(address pc) {
 643   RelocIterator iter(this, pc, pc+1);
 644   while (iter.next()) {
 645     relocInfo::relocType t = iter.type();
 646     if (t == relocInfo::poll_return_type || t == relocInfo::poll_type)
 647       return true;
 648   }
 649   return false;
 650 }
 651 
 652 void nmethod::verify_oop_relocations() {
 653   // Ensure sure that the code matches the current oop values
 654   RelocIterator iter(this, nullptr, nullptr);
 655   while (iter.next()) {
 656     if (iter.type() == relocInfo::oop_type) {
 657       oop_Relocation* reloc = iter.oop_reloc();
 658       if (!reloc->oop_is_immediate()) {
 659         reloc->verify_oop_relocation();
 660       }
 661     }
 662   }
 663 }
 664 
 665 
 666 ScopeDesc* nmethod::scope_desc_at(address pc) {
 667   PcDesc* pd = pc_desc_at(pc);
 668   guarantee(pd != nullptr, "scope must be present");
 669   return new ScopeDesc(this, pd);
 670 }
 671 
 672 ScopeDesc* nmethod::scope_desc_near(address pc) {
 673   PcDesc* pd = pc_desc_near(pc);
 674   guarantee(pd != nullptr, "scope must be present");
 675   return new ScopeDesc(this, pd);
 676 }
 677 
 678 address nmethod::oops_reloc_begin() const {
 679   // If the method is not entrant then a JMP is plastered over the
 680   // first few bytes.  If an oop in the old code was there, that oop
 681   // should not get GC'd.  Skip the first few bytes of oops on
 682   // not-entrant methods.
 683   if (frame_complete_offset() != CodeOffsets::frame_never_safe &&
 684       code_begin() + frame_complete_offset() >
 685       verified_entry_point() + NativeJump::instruction_size)
 686   {
 687     // If we have a frame_complete_offset after the native jump, then there
 688     // is no point trying to look for oops before that. This is a requirement
 689     // for being allowed to scan oops concurrently.
 690     return code_begin() + frame_complete_offset();
 691   }
 692 
 693   address low_boundary = verified_entry_point();
 694   return low_boundary;
 695 }
 696 
 697 // Method that knows how to preserve outgoing arguments at call. This method must be
 698 // called with a frame corresponding to a Java invoke
 699 void nmethod::preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f) {
 700   if (method() == nullptr) {
 701     return;
 702   }
 703 
 704   // handle the case of an anchor explicitly set in continuation code that doesn't have a callee
 705   JavaThread* thread = reg_map->thread();
 706   if ((thread->has_last_Java_frame() && fr.sp() == thread->last_Java_sp())
 707       JVMTI_ONLY(|| (method()->is_continuation_enter_intrinsic() && thread->on_monitor_waited_event()))) {
 708     return;
 709   }
 710 
 711   if (!method()->is_native()) {
 712     address pc = fr.pc();
 713     bool has_receiver, has_appendix;
 714     Symbol* signature;
 715 
 716     // The method attached by JIT-compilers should be used, if present.
 717     // Bytecode can be inaccurate in such case.
 718     Method* callee = attached_method_before_pc(pc);
 719     if (callee != nullptr) {
 720       has_receiver = !(callee->access_flags().is_static());
 721       has_appendix = false;
 722       signature    = callee->signature();
 723 
 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   if (jvmci_skip_profile_deopt()) {
1959     return;
1960   }
1961 #endif
1962   Method* m = method();
1963   if (m == nullptr)  return;
1964   MethodData* mdo = m->method_data();
1965   if (mdo == nullptr)  return;
1966   // There is a benign race here.  See comments in methodData.hpp.
1967   mdo->inc_decompile_count();
1968 }
1969 
1970 bool nmethod::try_transition(signed char new_state_int) {
1971   signed char new_state = new_state_int;
1972   assert_lock_strong(NMethodState_lock);
1973   signed char old_state = _state;
1974   if (old_state >= new_state) {
1975     // Ensure monotonicity of transitions.
1976     return false;
1977   }
1978   Atomic::store(&_state, new_state);
1979   return true;
1980 }
1981 
1982 void nmethod::invalidate_osr_method() {
1983   assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod");
1984   // Remove from list of active nmethods
1985   if (method() != nullptr) {
1986     method()->method_holder()->remove_osr_nmethod(this);
1987   }
1988 }
1989 
1990 void nmethod::log_state_change(InvalidationReason invalidation_reason) const {
1991   if (LogCompilation) {
1992     if (xtty != nullptr) {
1993       ttyLocker ttyl;  // keep the following output all in one block
1994       xtty->begin_elem("make_not_entrant thread='%zu' reason='%s'",
1995                        os::current_thread_id(), invalidation_reason_to_string(invalidation_reason));
1996       log_identity(xtty);
1997       xtty->stamp();
1998       xtty->end_elem();
1999     }
2000   }
2001 
2002   ResourceMark rm;
2003   stringStream ss(NEW_RESOURCE_ARRAY(char, 256), 256);
2004   ss.print("made not entrant: %s", invalidation_reason_to_string(invalidation_reason));
2005 
2006   CompileTask::print_ul(this, ss.freeze());
2007   if (PrintCompilation) {
2008     print_on_with_msg(tty, ss.freeze());
2009   }
2010 }
2011 
2012 void nmethod::unlink_from_method() {
2013   if (method() != nullptr) {
2014     method()->unlink_code(this);
2015   }
2016 }
2017 
2018 // Invalidate code
2019 bool nmethod::make_not_entrant(InvalidationReason invalidation_reason) {
2020   // This can be called while the system is already at a safepoint which is ok
2021   NoSafepointVerifier nsv;
2022 
2023   if (is_unloading()) {
2024     // If the nmethod is unloading, then it is already not entrant through
2025     // the nmethod entry barriers. No need to do anything; GC will unload it.
2026     return false;
2027   }
2028 
2029   if (Atomic::load(&_state) == not_entrant) {
2030     // Avoid taking the lock if already in required state.
2031     // This is safe from races because the state is an end-state,
2032     // which the nmethod cannot back out of once entered.
2033     // No need for fencing either.
2034     return false;
2035   }
2036 
2037   {
2038     // Enter critical section.  Does not block for safepoint.
2039     ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
2040 
2041     if (Atomic::load(&_state) == not_entrant) {
2042       // another thread already performed this transition so nothing
2043       // to do, but return false to indicate this.
2044       return false;
2045     }
2046 
2047     if (is_osr_method()) {
2048       // This logic is equivalent to the logic below for patching the
2049       // verified entry point of regular methods.
2050       // this effectively makes the osr nmethod not entrant
2051       invalidate_osr_method();
2052     } else {
2053       // The caller can be calling the method statically or through an inline
2054       // cache call.
2055       BarrierSet::barrier_set()->barrier_set_nmethod()->make_not_entrant(this);
2056     }
2057 
2058     if (update_recompile_counts()) {
2059       // Mark the method as decompiled.
2060       inc_decompile_count();
2061     }
2062 
2063     BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2064     if (bs_nm == nullptr || !bs_nm->supports_entry_barrier(this)) {
2065       // If nmethod entry barriers are not supported, we won't mark
2066       // nmethods as on-stack when they become on-stack. So we
2067       // degrade to a less accurate flushing strategy, for now.
2068       mark_as_maybe_on_stack();
2069     }
2070 
2071     // Change state
2072     bool success = try_transition(not_entrant);
2073     assert(success, "Transition can't fail");
2074 
2075     // Log the transition once
2076     log_state_change(invalidation_reason);
2077 
2078     // Remove nmethod from method.
2079     unlink_from_method();
2080 
2081   } // leave critical region under NMethodState_lock
2082 
2083 #if INCLUDE_JVMCI
2084   // Invalidate can't occur while holding the NMethodState_lock
2085   JVMCINMethodData* nmethod_data = jvmci_nmethod_data();
2086   if (nmethod_data != nullptr) {
2087     nmethod_data->invalidate_nmethod_mirror(this, invalidation_reason);
2088   }
2089 #endif
2090 
2091 #ifdef ASSERT
2092   if (is_osr_method() && method() != nullptr) {
2093     // Make sure osr nmethod is invalidated, i.e. not on the list
2094     bool found = method()->method_holder()->remove_osr_nmethod(this);
2095     assert(!found, "osr nmethod should have been invalidated");
2096   }
2097 #endif
2098 
2099   return true;
2100 }
2101 
2102 // For concurrent GCs, there must be a handshake between unlink and flush
2103 void nmethod::unlink() {
2104   if (is_unlinked()) {
2105     // Already unlinked.
2106     return;
2107   }
2108 
2109   flush_dependencies();
2110 
2111   // unlink_from_method will take the NMethodState_lock.
2112   // In this case we don't strictly need it when unlinking nmethods from
2113   // the Method, because it is only concurrently unlinked by
2114   // the entry barrier, which acquires the per nmethod lock.
2115   unlink_from_method();
2116 
2117   if (is_osr_method()) {
2118     invalidate_osr_method();
2119   }
2120 
2121 #if INCLUDE_JVMCI
2122   // Clear the link between this nmethod and a HotSpotNmethod mirror
2123   JVMCINMethodData* nmethod_data = jvmci_nmethod_data();
2124   if (nmethod_data != nullptr) {
2125     nmethod_data->invalidate_nmethod_mirror(this, is_cold() ?
2126             nmethod::InvalidationReason::UNLOADING_COLD :
2127             nmethod::InvalidationReason::UNLOADING);
2128   }
2129 #endif
2130 
2131   // Post before flushing as jmethodID is being used
2132   post_compiled_method_unload();
2133 
2134   // Register for flushing when it is safe. For concurrent class unloading,
2135   // that would be after the unloading handshake, and for STW class unloading
2136   // that would be when getting back to the VM thread.
2137   ClassUnloadingContext::context()->register_unlinked_nmethod(this);
2138 }
2139 
2140 void nmethod::purge(bool unregister_nmethod) {
2141 
2142   MutexLocker ml(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2143 
2144   // completely deallocate this method
2145   Events::log_nmethod_flush(Thread::current(), "flushing %s nmethod " INTPTR_FORMAT, is_osr_method() ? "osr" : "", p2i(this));
2146 
2147   LogTarget(Debug, codecache) lt;
2148   if (lt.is_enabled()) {
2149     ResourceMark rm;
2150     LogStream ls(lt);
2151     const char* method_name = method()->name()->as_C_string();
2152     const size_t codecache_capacity = CodeCache::capacity()/1024;
2153     const size_t codecache_free_space = CodeCache::unallocated_capacity(CodeCache::get_code_blob_type(this))/1024;
2154     ls.print("Flushing nmethod %6d/" INTPTR_FORMAT ", level=%d, osr=%d, cold=%d, epoch=" UINT64_FORMAT ", cold_count=" UINT64_FORMAT ". "
2155               "Cache capacity: %zuKb, free space: %zuKb. method %s (%s)",
2156               _compile_id, p2i(this), _comp_level, is_osr_method(), is_cold(), _gc_epoch, CodeCache::cold_gc_count(),
2157               codecache_capacity, codecache_free_space, method_name, compiler_name());
2158   }
2159 
2160   // We need to deallocate any ExceptionCache data.
2161   // Note that we do not need to grab the nmethod lock for this, it
2162   // better be thread safe if we're disposing of it!
2163   ExceptionCache* ec = exception_cache();
2164   while(ec != nullptr) {
2165     ExceptionCache* next = ec->next();
2166     delete ec;
2167     ec = next;
2168   }
2169   if (_pc_desc_container != nullptr) {
2170     delete _pc_desc_container;
2171   }
2172   delete[] _compiled_ic_data;
2173 
2174   if (_immutable_data != blob_end()) {
2175     os::free(_immutable_data);
2176     _immutable_data = blob_end(); // Valid not null address
2177   }
2178   if (unregister_nmethod) {
2179     Universe::heap()->unregister_nmethod(this);
2180   }
2181   CodeCache::unregister_old_nmethod(this);
2182 
2183   JVMCI_ONLY( _metadata_size = 0; )
2184   CodeBlob::purge();
2185 }
2186 
2187 oop nmethod::oop_at(int index) const {
2188   if (index == 0) {
2189     return nullptr;
2190   }
2191 
2192   BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2193   return bs_nm->oop_load_no_keepalive(this, index);
2194 }
2195 
2196 oop nmethod::oop_at_phantom(int index) const {
2197   if (index == 0) {
2198     return nullptr;
2199   }
2200 
2201   BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2202   return bs_nm->oop_load_phantom(this, index);
2203 }
2204 
2205 //
2206 // Notify all classes this nmethod is dependent on that it is no
2207 // longer dependent.
2208 
2209 void nmethod::flush_dependencies() {
2210   if (!has_flushed_dependencies()) {
2211     set_has_flushed_dependencies(true);
2212     for (Dependencies::DepStream deps(this); deps.next(); ) {
2213       if (deps.type() == Dependencies::call_site_target_value) {
2214         // CallSite dependencies are managed on per-CallSite instance basis.
2215         oop call_site = deps.argument_oop(0);
2216         MethodHandles::clean_dependency_context(call_site);
2217       } else {
2218         InstanceKlass* ik = deps.context_type();
2219         if (ik == nullptr) {
2220           continue;  // ignore things like evol_method
2221         }
2222         // During GC liveness of dependee determines class that needs to be updated.
2223         // The GC may clean dependency contexts concurrently and in parallel.
2224         ik->clean_dependency_context();
2225       }
2226     }
2227   }
2228 }
2229 
2230 void nmethod::post_compiled_method(CompileTask* task) {
2231   task->mark_success();
2232   task->set_nm_content_size(content_size());
2233   task->set_nm_insts_size(insts_size());
2234   task->set_nm_total_size(total_size());
2235 
2236   // JVMTI -- compiled method notification (must be done outside lock)
2237   post_compiled_method_load_event();
2238 
2239   if (CompilationLog::log() != nullptr) {
2240     CompilationLog::log()->log_nmethod(JavaThread::current(), this);
2241   }
2242 
2243   const DirectiveSet* directive = task->directive();
2244   maybe_print_nmethod(directive);
2245 }
2246 
2247 // ------------------------------------------------------------------
2248 // post_compiled_method_load_event
2249 // new method for install_code() path
2250 // Transfer information from compilation to jvmti
2251 void nmethod::post_compiled_method_load_event(JvmtiThreadState* state) {
2252   // This is a bad time for a safepoint.  We don't want
2253   // this nmethod to get unloaded while we're queueing the event.
2254   NoSafepointVerifier nsv;
2255 
2256   Method* m = method();
2257   HOTSPOT_COMPILED_METHOD_LOAD(
2258       (char *) m->klass_name()->bytes(),
2259       m->klass_name()->utf8_length(),
2260       (char *) m->name()->bytes(),
2261       m->name()->utf8_length(),
2262       (char *) m->signature()->bytes(),
2263       m->signature()->utf8_length(),
2264       insts_begin(), insts_size());
2265 
2266 
2267   if (JvmtiExport::should_post_compiled_method_load()) {
2268     // Only post unload events if load events are found.
2269     set_load_reported();
2270     // If a JavaThread hasn't been passed in, let the Service thread
2271     // (which is a real Java thread) post the event
2272     JvmtiDeferredEvent event = JvmtiDeferredEvent::compiled_method_load_event(this);
2273     if (state == nullptr) {
2274       // Execute any barrier code for this nmethod as if it's called, since
2275       // keeping it alive looks like stack walking.
2276       run_nmethod_entry_barrier();
2277       ServiceThread::enqueue_deferred_event(&event);
2278     } else {
2279       // This enters the nmethod barrier outside in the caller.
2280       state->enqueue_event(&event);
2281     }
2282   }
2283 }
2284 
2285 void nmethod::post_compiled_method_unload() {
2286   assert(_method != nullptr, "just checking");
2287   DTRACE_METHOD_UNLOAD_PROBE(method());
2288 
2289   // If a JVMTI agent has enabled the CompiledMethodUnload event then
2290   // post the event. The Method* will not be valid when this is freed.
2291 
2292   // Don't bother posting the unload if the load event wasn't posted.
2293   if (load_reported() && JvmtiExport::should_post_compiled_method_unload()) {
2294     JvmtiDeferredEvent event =
2295       JvmtiDeferredEvent::compiled_method_unload_event(
2296           method()->jmethod_id(), insts_begin());
2297     ServiceThread::enqueue_deferred_event(&event);
2298   }
2299 }
2300 
2301 // Iterate over metadata calling this function.   Used by RedefineClasses
2302 void nmethod::metadata_do(MetadataClosure* f) {
2303   {
2304     // Visit all immediate references that are embedded in the instruction stream.
2305     RelocIterator iter(this, oops_reloc_begin());
2306     while (iter.next()) {
2307       if (iter.type() == relocInfo::metadata_type) {
2308         metadata_Relocation* r = iter.metadata_reloc();
2309         // In this metadata, we must only follow those metadatas directly embedded in
2310         // the code.  Other metadatas (oop_index>0) are seen as part of
2311         // the metadata section below.
2312         assert(1 == (r->metadata_is_immediate()) +
2313                (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()),
2314                "metadata must be found in exactly one place");
2315         if (r->metadata_is_immediate() && r->metadata_value() != nullptr) {
2316           Metadata* md = r->metadata_value();
2317           if (md != _method) f->do_metadata(md);
2318         }
2319       } else if (iter.type() == relocInfo::virtual_call_type) {
2320         // Check compiledIC holders associated with this nmethod
2321         ResourceMark rm;
2322         CompiledIC *ic = CompiledIC_at(&iter);
2323         ic->metadata_do(f);
2324       }
2325     }
2326   }
2327 
2328   // Visit the metadata section
2329   for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
2330     if (*p == Universe::non_oop_word() || *p == nullptr)  continue;  // skip non-oops
2331     Metadata* md = *p;
2332     f->do_metadata(md);
2333   }
2334 
2335   // Visit metadata not embedded in the other places.
2336   if (_method != nullptr) f->do_metadata(_method);
2337 }
2338 
2339 // Heuristic for nuking nmethods even though their oops are live.
2340 // Main purpose is to reduce code cache pressure and get rid of
2341 // nmethods that don't seem to be all that relevant any longer.
2342 bool nmethod::is_cold() {
2343   if (!MethodFlushing || is_native_method() || is_not_installed()) {
2344     // No heuristic unloading at all
2345     return false;
2346   }
2347 
2348   if (!is_maybe_on_stack() && is_not_entrant()) {
2349     // Not entrant nmethods that are not on any stack can just
2350     // be removed
2351     return true;
2352   }
2353 
2354   BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2355   if (bs_nm == nullptr || !bs_nm->supports_entry_barrier(this)) {
2356     // On platforms that don't support nmethod entry barriers, we can't
2357     // trust the temporal aspect of the gc epochs. So we can't detect
2358     // cold nmethods on such platforms.
2359     return false;
2360   }
2361 
2362   if (!UseCodeCacheFlushing) {
2363     // Bail out if we don't heuristically remove nmethods
2364     return false;
2365   }
2366 
2367   // Other code can be phased out more gradually after N GCs
2368   return CodeCache::previous_completed_gc_marking_cycle() > _gc_epoch + 2 * CodeCache::cold_gc_count();
2369 }
2370 
2371 // The _is_unloading_state encodes a tuple comprising the unloading cycle
2372 // and the result of IsUnloadingBehaviour::is_unloading() for that cycle.
2373 // This is the bit layout of the _is_unloading_state byte: 00000CCU
2374 // CC refers to the cycle, which has 2 bits, and U refers to the result of
2375 // IsUnloadingBehaviour::is_unloading() for that unloading cycle.
2376 
2377 class IsUnloadingState: public AllStatic {
2378   static const uint8_t _is_unloading_mask = 1;
2379   static const uint8_t _is_unloading_shift = 0;
2380   static const uint8_t _unloading_cycle_mask = 6;
2381   static const uint8_t _unloading_cycle_shift = 1;
2382 
2383   static uint8_t set_is_unloading(uint8_t state, bool value) {
2384     state &= (uint8_t)~_is_unloading_mask;
2385     if (value) {
2386       state |= 1 << _is_unloading_shift;
2387     }
2388     assert(is_unloading(state) == value, "unexpected unloading cycle overflow");
2389     return state;
2390   }
2391 
2392   static uint8_t set_unloading_cycle(uint8_t state, uint8_t value) {
2393     state &= (uint8_t)~_unloading_cycle_mask;
2394     state |= (uint8_t)(value << _unloading_cycle_shift);
2395     assert(unloading_cycle(state) == value, "unexpected unloading cycle overflow");
2396     return state;
2397   }
2398 
2399 public:
2400   static bool is_unloading(uint8_t state) { return (state & _is_unloading_mask) >> _is_unloading_shift == 1; }
2401   static uint8_t unloading_cycle(uint8_t state) { return (state & _unloading_cycle_mask) >> _unloading_cycle_shift; }
2402 
2403   static uint8_t create(bool is_unloading, uint8_t unloading_cycle) {
2404     uint8_t state = 0;
2405     state = set_is_unloading(state, is_unloading);
2406     state = set_unloading_cycle(state, unloading_cycle);
2407     return state;
2408   }
2409 };
2410 
2411 bool nmethod::is_unloading() {
2412   uint8_t state = Atomic::load(&_is_unloading_state);
2413   bool state_is_unloading = IsUnloadingState::is_unloading(state);
2414   if (state_is_unloading) {
2415     return true;
2416   }
2417   uint8_t state_unloading_cycle = IsUnloadingState::unloading_cycle(state);
2418   uint8_t current_cycle = CodeCache::unloading_cycle();
2419   if (state_unloading_cycle == current_cycle) {
2420     return false;
2421   }
2422 
2423   // The IsUnloadingBehaviour is responsible for calculating if the nmethod
2424   // should be unloaded. This can be either because there is a dead oop,
2425   // or because is_cold() heuristically determines it is time to unload.
2426   state_unloading_cycle = current_cycle;
2427   state_is_unloading = IsUnloadingBehaviour::is_unloading(this);
2428   uint8_t new_state = IsUnloadingState::create(state_is_unloading, state_unloading_cycle);
2429 
2430   // Note that if an nmethod has dead oops, everyone will agree that the
2431   // nmethod is_unloading. However, the is_cold heuristics can yield
2432   // different outcomes, so we guard the computed result with a CAS
2433   // to ensure all threads have a shared view of whether an nmethod
2434   // is_unloading or not.
2435   uint8_t found_state = Atomic::cmpxchg(&_is_unloading_state, state, new_state, memory_order_relaxed);
2436 
2437   if (found_state == state) {
2438     // First to change state, we win
2439     return state_is_unloading;
2440   } else {
2441     // State already set, so use it
2442     return IsUnloadingState::is_unloading(found_state);
2443   }
2444 }
2445 
2446 void nmethod::clear_unloading_state() {
2447   uint8_t state = IsUnloadingState::create(false, CodeCache::unloading_cycle());
2448   Atomic::store(&_is_unloading_state, state);
2449 }
2450 
2451 
2452 // This is called at the end of the strong tracing/marking phase of a
2453 // GC to unload an nmethod if it contains otherwise unreachable
2454 // oops or is heuristically found to be not important.
2455 void nmethod::do_unloading(bool unloading_occurred) {
2456   // Make sure the oop's ready to receive visitors
2457   if (is_unloading()) {
2458     unlink();
2459   } else {
2460     unload_nmethod_caches(unloading_occurred);
2461     BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2462     if (bs_nm != nullptr) {
2463       bs_nm->disarm(this);
2464     }
2465   }
2466 }
2467 
2468 void nmethod::oops_do(OopClosure* f) {
2469   // Prevent extra code cache walk for platforms that don't have immediate oops.
2470   if (relocInfo::mustIterateImmediateOopsInCode()) {
2471     RelocIterator iter(this, oops_reloc_begin());
2472 
2473     while (iter.next()) {
2474       if (iter.type() == relocInfo::oop_type ) {
2475         oop_Relocation* r = iter.oop_reloc();
2476         // In this loop, we must only follow those oops directly embedded in
2477         // the code.  Other oops (oop_index>0) are seen as part of scopes_oops.
2478         assert(1 == (r->oop_is_immediate()) +
2479                (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
2480                "oop must be found in exactly one place");
2481         if (r->oop_is_immediate() && r->oop_value() != nullptr) {
2482           f->do_oop(r->oop_addr());
2483         }
2484       }
2485     }
2486   }
2487 
2488   // Scopes
2489   // This includes oop constants not inlined in the code stream.
2490   for (oop* p = oops_begin(); p < oops_end(); p++) {
2491     if (*p == Universe::non_oop_word())  continue;  // skip non-oops
2492     f->do_oop(p);
2493   }
2494 }
2495 
2496 void nmethod::follow_nmethod(OopIterateClosure* cl) {
2497   // Process oops in the nmethod
2498   oops_do(cl);
2499 
2500   // CodeCache unloading support
2501   mark_as_maybe_on_stack();
2502 
2503   BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2504   bs_nm->disarm(this);
2505 
2506   // There's an assumption made that this function is not used by GCs that
2507   // relocate objects, and therefore we don't call fix_oop_relocations.
2508 }
2509 
2510 nmethod* volatile nmethod::_oops_do_mark_nmethods;
2511 
2512 void nmethod::oops_do_log_change(const char* state) {
2513   LogTarget(Trace, gc, nmethod) lt;
2514   if (lt.is_enabled()) {
2515     LogStream ls(lt);
2516     CompileTask::print(&ls, this, state, true /* short_form */);
2517   }
2518 }
2519 
2520 bool nmethod::oops_do_try_claim() {
2521   if (oops_do_try_claim_weak_request()) {
2522     nmethod* result = oops_do_try_add_to_list_as_weak_done();
2523     assert(result == nullptr, "adding to global list as weak done must always succeed.");
2524     return true;
2525   }
2526   return false;
2527 }
2528 
2529 bool nmethod::oops_do_try_claim_weak_request() {
2530   assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2531 
2532   if ((_oops_do_mark_link == nullptr) &&
2533       (Atomic::replace_if_null(&_oops_do_mark_link, mark_link(this, claim_weak_request_tag)))) {
2534     oops_do_log_change("oops_do, mark weak request");
2535     return true;
2536   }
2537   return false;
2538 }
2539 
2540 void nmethod::oops_do_set_strong_done(nmethod* old_head) {
2541   _oops_do_mark_link = mark_link(old_head, claim_strong_done_tag);
2542 }
2543 
2544 nmethod::oops_do_mark_link* nmethod::oops_do_try_claim_strong_done() {
2545   assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2546 
2547   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));
2548   if (old_next == nullptr) {
2549     oops_do_log_change("oops_do, mark strong done");
2550   }
2551   return old_next;
2552 }
2553 
2554 nmethod::oops_do_mark_link* nmethod::oops_do_try_add_strong_request(nmethod::oops_do_mark_link* next) {
2555   assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2556   assert(next == mark_link(this, claim_weak_request_tag), "Should be claimed as weak");
2557 
2558   oops_do_mark_link* old_next = Atomic::cmpxchg(&_oops_do_mark_link, next, mark_link(this, claim_strong_request_tag));
2559   if (old_next == next) {
2560     oops_do_log_change("oops_do, mark strong request");
2561   }
2562   return old_next;
2563 }
2564 
2565 bool nmethod::oops_do_try_claim_weak_done_as_strong_done(nmethod::oops_do_mark_link* next) {
2566   assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2567   assert(extract_state(next) == claim_weak_done_tag, "Should be claimed as weak done");
2568 
2569   oops_do_mark_link* old_next = Atomic::cmpxchg(&_oops_do_mark_link, next, mark_link(extract_nmethod(next), claim_strong_done_tag));
2570   if (old_next == next) {
2571     oops_do_log_change("oops_do, mark weak done -> mark strong done");
2572     return true;
2573   }
2574   return false;
2575 }
2576 
2577 nmethod* nmethod::oops_do_try_add_to_list_as_weak_done() {
2578   assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2579 
2580   assert(extract_state(_oops_do_mark_link) == claim_weak_request_tag ||
2581          extract_state(_oops_do_mark_link) == claim_strong_request_tag,
2582          "must be but is nmethod " PTR_FORMAT " %u", p2i(extract_nmethod(_oops_do_mark_link)), extract_state(_oops_do_mark_link));
2583 
2584   nmethod* old_head = Atomic::xchg(&_oops_do_mark_nmethods, this);
2585   // Self-loop if needed.
2586   if (old_head == nullptr) {
2587     old_head = this;
2588   }
2589   // Try to install end of list and weak done tag.
2590   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)) {
2591     oops_do_log_change("oops_do, mark weak done");
2592     return nullptr;
2593   } else {
2594     return old_head;
2595   }
2596 }
2597 
2598 void nmethod::oops_do_add_to_list_as_strong_done() {
2599   assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2600 
2601   nmethod* old_head = Atomic::xchg(&_oops_do_mark_nmethods, this);
2602   // Self-loop if needed.
2603   if (old_head == nullptr) {
2604     old_head = this;
2605   }
2606   assert(_oops_do_mark_link == mark_link(this, claim_strong_done_tag), "must be but is nmethod " PTR_FORMAT " state %u",
2607          p2i(extract_nmethod(_oops_do_mark_link)), extract_state(_oops_do_mark_link));
2608 
2609   oops_do_set_strong_done(old_head);
2610 }
2611 
2612 void nmethod::oops_do_process_weak(OopsDoProcessor* p) {
2613   if (!oops_do_try_claim_weak_request()) {
2614     // Failed to claim for weak processing.
2615     oops_do_log_change("oops_do, mark weak request fail");
2616     return;
2617   }
2618 
2619   p->do_regular_processing(this);
2620 
2621   nmethod* old_head = oops_do_try_add_to_list_as_weak_done();
2622   if (old_head == nullptr) {
2623     return;
2624   }
2625   oops_do_log_change("oops_do, mark weak done fail");
2626   // Adding to global list failed, another thread added a strong request.
2627   assert(extract_state(_oops_do_mark_link) == claim_strong_request_tag,
2628          "must be but is %u", extract_state(_oops_do_mark_link));
2629 
2630   oops_do_log_change("oops_do, mark weak request -> mark strong done");
2631 
2632   oops_do_set_strong_done(old_head);
2633   // Do missing strong processing.
2634   p->do_remaining_strong_processing(this);
2635 }
2636 
2637 void nmethod::oops_do_process_strong(OopsDoProcessor* p) {
2638   oops_do_mark_link* next_raw = oops_do_try_claim_strong_done();
2639   if (next_raw == nullptr) {
2640     p->do_regular_processing(this);
2641     oops_do_add_to_list_as_strong_done();
2642     return;
2643   }
2644   // Claim failed. Figure out why and handle it.
2645   if (oops_do_has_weak_request(next_raw)) {
2646     oops_do_mark_link* old = next_raw;
2647     // Claim failed because being weak processed (state == "weak request").
2648     // Try to request deferred strong processing.
2649     next_raw = oops_do_try_add_strong_request(old);
2650     if (next_raw == old) {
2651       // Successfully requested deferred strong processing.
2652       return;
2653     }
2654     // Failed because of a concurrent transition. No longer in "weak request" state.
2655   }
2656   if (oops_do_has_any_strong_state(next_raw)) {
2657     // Already claimed for strong processing or requested for such.
2658     return;
2659   }
2660   if (oops_do_try_claim_weak_done_as_strong_done(next_raw)) {
2661     // Successfully claimed "weak done" as "strong done". Do the missing marking.
2662     p->do_remaining_strong_processing(this);
2663     return;
2664   }
2665   // Claim failed, some other thread got it.
2666 }
2667 
2668 void nmethod::oops_do_marking_prologue() {
2669   assert_at_safepoint();
2670 
2671   log_trace(gc, nmethod)("oops_do_marking_prologue");
2672   assert(_oops_do_mark_nmethods == nullptr, "must be empty");
2673 }
2674 
2675 void nmethod::oops_do_marking_epilogue() {
2676   assert_at_safepoint();
2677 
2678   nmethod* next = _oops_do_mark_nmethods;
2679   _oops_do_mark_nmethods = nullptr;
2680   if (next != nullptr) {
2681     nmethod* cur;
2682     do {
2683       cur = next;
2684       next = extract_nmethod(cur->_oops_do_mark_link);
2685       cur->_oops_do_mark_link = nullptr;
2686       DEBUG_ONLY(cur->verify_oop_relocations());
2687 
2688       LogTarget(Trace, gc, nmethod) lt;
2689       if (lt.is_enabled()) {
2690         LogStream ls(lt);
2691         CompileTask::print(&ls, cur, "oops_do, unmark", /*short_form:*/ true);
2692       }
2693       // End if self-loop has been detected.
2694     } while (cur != next);
2695   }
2696   log_trace(gc, nmethod)("oops_do_marking_epilogue");
2697 }
2698 
2699 inline bool includes(void* p, void* from, void* to) {
2700   return from <= p && p < to;
2701 }
2702 
2703 
2704 void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) {
2705   assert(count >= 2, "must be sentinel values, at least");
2706 
2707 #ifdef ASSERT
2708   // must be sorted and unique; we do a binary search in find_pc_desc()
2709   int prev_offset = pcs[0].pc_offset();
2710   assert(prev_offset == PcDesc::lower_offset_limit,
2711          "must start with a sentinel");
2712   for (int i = 1; i < count; i++) {
2713     int this_offset = pcs[i].pc_offset();
2714     assert(this_offset > prev_offset, "offsets must be sorted");
2715     prev_offset = this_offset;
2716   }
2717   assert(prev_offset == PcDesc::upper_offset_limit,
2718          "must end with a sentinel");
2719 #endif //ASSERT
2720 
2721   // Search for MethodHandle invokes and tag the nmethod.
2722   for (int i = 0; i < count; i++) {
2723     if (pcs[i].is_method_handle_invoke()) {
2724       set_has_method_handle_invokes(true);
2725       break;
2726     }
2727   }
2728   assert(has_method_handle_invokes() == (_deopt_mh_handler_offset != -1), "must have deopt mh handler");
2729 
2730   int size = count * sizeof(PcDesc);
2731   assert(scopes_pcs_size() >= size, "oob");
2732   memcpy(scopes_pcs_begin(), pcs, size);
2733 
2734   // Adjust the final sentinel downward.
2735   PcDesc* last_pc = &scopes_pcs_begin()[count-1];
2736   assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity");
2737   last_pc->set_pc_offset(content_size() + 1);
2738   for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) {
2739     // Fill any rounding gaps with copies of the last record.
2740     last_pc[1] = last_pc[0];
2741   }
2742   // The following assert could fail if sizeof(PcDesc) is not
2743   // an integral multiple of oopSize (the rounding term).
2744   // If it fails, change the logic to always allocate a multiple
2745   // of sizeof(PcDesc), and fill unused words with copies of *last_pc.
2746   assert(last_pc + 1 == scopes_pcs_end(), "must match exactly");
2747 }
2748 
2749 void nmethod::copy_scopes_data(u_char* buffer, int size) {
2750   assert(scopes_data_size() >= size, "oob");
2751   memcpy(scopes_data_begin(), buffer, size);
2752 }
2753 
2754 #ifdef ASSERT
2755 static PcDesc* linear_search(int pc_offset, bool approximate, PcDesc* lower, PcDesc* upper) {
2756   PcDesc* res = nullptr;
2757   assert(lower != nullptr && lower->pc_offset() == PcDesc::lower_offset_limit,
2758          "must start with a sentinel");
2759   // lower + 1 to exclude initial sentinel
2760   for (PcDesc* p = lower + 1; p < upper; p++) {
2761     NOT_PRODUCT(--pc_nmethod_stats.pc_desc_tests);  // don't count this call to match_desc
2762     if (match_desc(p, pc_offset, approximate)) {
2763       if (res == nullptr) {
2764         res = p;
2765       } else {
2766         res = (PcDesc*) badAddress;
2767       }
2768     }
2769   }
2770   return res;
2771 }
2772 #endif
2773 
2774 
2775 #ifndef PRODUCT
2776 // Version of method to collect statistic
2777 PcDesc* PcDescContainer::find_pc_desc(address pc, bool approximate, address code_begin,
2778                                       PcDesc* lower, PcDesc* upper) {
2779   ++pc_nmethod_stats.pc_desc_queries;
2780   if (approximate) ++pc_nmethod_stats.pc_desc_approx;
2781 
2782   PcDesc* desc = _pc_desc_cache.last_pc_desc();
2783   assert(desc != nullptr, "PcDesc cache should be initialized already");
2784   if (desc->pc_offset() == (pc - code_begin)) {
2785     // Cached value matched
2786     ++pc_nmethod_stats.pc_desc_tests;
2787     ++pc_nmethod_stats.pc_desc_repeats;
2788     return desc;
2789   }
2790   return find_pc_desc_internal(pc, approximate, code_begin, lower, upper);
2791 }
2792 #endif
2793 
2794 // Finds a PcDesc with real-pc equal to "pc"
2795 PcDesc* PcDescContainer::find_pc_desc_internal(address pc, bool approximate, address code_begin,
2796                                                PcDesc* lower_incl, PcDesc* upper_incl) {
2797   if ((pc < code_begin) ||
2798       (pc - code_begin) >= (ptrdiff_t) PcDesc::upper_offset_limit) {
2799     return nullptr;  // PC is wildly out of range
2800   }
2801   int pc_offset = (int) (pc - code_begin);
2802 
2803   // Check the PcDesc cache if it contains the desired PcDesc
2804   // (This as an almost 100% hit rate.)
2805   PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate);
2806   if (res != nullptr) {
2807     assert(res == linear_search(pc_offset, approximate, lower_incl, upper_incl), "cache ok");
2808     return res;
2809   }
2810 
2811   // Fallback algorithm: quasi-linear search for the PcDesc
2812   // Find the last pc_offset less than the given offset.
2813   // The successor must be the required match, if there is a match at all.
2814   // (Use a fixed radix to avoid expensive affine pointer arithmetic.)
2815   PcDesc* lower = lower_incl;     // this is initial sentinel
2816   PcDesc* upper = upper_incl - 1; // exclude final sentinel
2817   if (lower >= upper)  return nullptr;  // no PcDescs at all
2818 
2819 #define assert_LU_OK \
2820   /* invariant on lower..upper during the following search: */ \
2821   assert(lower->pc_offset() <  pc_offset, "sanity"); \
2822   assert(upper->pc_offset() >= pc_offset, "sanity")
2823   assert_LU_OK;
2824 
2825   // Use the last successful return as a split point.
2826   PcDesc* mid = _pc_desc_cache.last_pc_desc();
2827   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
2828   if (mid->pc_offset() < pc_offset) {
2829     lower = mid;
2830   } else {
2831     upper = mid;
2832   }
2833 
2834   // Take giant steps at first (4096, then 256, then 16, then 1)
2835   const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ DEBUG_ONLY(-1);
2836   const int RADIX = (1 << LOG2_RADIX);
2837   for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) {
2838     while ((mid = lower + step) < upper) {
2839       assert_LU_OK;
2840       NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
2841       if (mid->pc_offset() < pc_offset) {
2842         lower = mid;
2843       } else {
2844         upper = mid;
2845         break;
2846       }
2847     }
2848     assert_LU_OK;
2849   }
2850 
2851   // Sneak up on the value with a linear search of length ~16.
2852   while (true) {
2853     assert_LU_OK;
2854     mid = lower + 1;
2855     NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
2856     if (mid->pc_offset() < pc_offset) {
2857       lower = mid;
2858     } else {
2859       upper = mid;
2860       break;
2861     }
2862   }
2863 #undef assert_LU_OK
2864 
2865   if (match_desc(upper, pc_offset, approximate)) {
2866     assert(upper == linear_search(pc_offset, approximate, lower_incl, upper_incl), "search mismatch");
2867     if (!Thread::current_in_asgct()) {
2868       // we don't want to modify the cache if we're in ASGCT
2869       // which is typically called in a signal handler
2870       _pc_desc_cache.add_pc_desc(upper);
2871     }
2872     return upper;
2873   } else {
2874     assert(nullptr == linear_search(pc_offset, approximate, lower_incl, upper_incl), "search mismatch");
2875     return nullptr;
2876   }
2877 }
2878 
2879 bool nmethod::check_dependency_on(DepChange& changes) {
2880   // What has happened:
2881   // 1) a new class dependee has been added
2882   // 2) dependee and all its super classes have been marked
2883   bool found_check = false;  // set true if we are upset
2884   for (Dependencies::DepStream deps(this); deps.next(); ) {
2885     // Evaluate only relevant dependencies.
2886     if (deps.spot_check_dependency_at(changes) != nullptr) {
2887       found_check = true;
2888       NOT_DEBUG(break);
2889     }
2890   }
2891   return found_check;
2892 }
2893 
2894 // Called from mark_for_deoptimization, when dependee is invalidated.
2895 bool nmethod::is_dependent_on_method(Method* dependee) {
2896   for (Dependencies::DepStream deps(this); deps.next(); ) {
2897     if (deps.type() != Dependencies::evol_method)
2898       continue;
2899     Method* method = deps.method_argument(0);
2900     if (method == dependee) return true;
2901   }
2902   return false;
2903 }
2904 
2905 void nmethod_init() {
2906   // make sure you didn't forget to adjust the filler fields
2907   assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word");
2908 }
2909 
2910 // -----------------------------------------------------------------------------
2911 // Verification
2912 
2913 class VerifyOopsClosure: public OopClosure {
2914   nmethod* _nm;
2915   bool     _ok;
2916 public:
2917   VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { }
2918   bool ok() { return _ok; }
2919   virtual void do_oop(oop* p) {
2920     if (oopDesc::is_oop_or_null(*p)) return;
2921     // Print diagnostic information before calling print_nmethod().
2922     // Assertions therein might prevent call from returning.
2923     tty->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)",
2924                   p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm));
2925     if (_ok) {
2926       _nm->print_nmethod(true);
2927       _ok = false;
2928     }
2929   }
2930   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
2931 };
2932 
2933 class VerifyMetadataClosure: public MetadataClosure {
2934  public:
2935   void do_metadata(Metadata* md) {
2936     if (md->is_method()) {
2937       Method* method = (Method*)md;
2938       assert(!method->is_old(), "Should not be installing old methods");
2939     }
2940   }
2941 };
2942 
2943 
2944 void nmethod::verify() {
2945   if (is_not_entrant())
2946     return;
2947 
2948   // assert(oopDesc::is_oop(method()), "must be valid");
2949 
2950   ResourceMark rm;
2951 
2952   if (!CodeCache::contains(this)) {
2953     fatal("nmethod at " INTPTR_FORMAT " not in zone", p2i(this));
2954   }
2955 
2956   if(is_native_method() )
2957     return;
2958 
2959   nmethod* nm = CodeCache::find_nmethod(verified_entry_point());
2960   if (nm != this) {
2961     fatal("find_nmethod did not find this nmethod (" INTPTR_FORMAT ")", p2i(this));
2962   }
2963 
2964   for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
2965     if (! p->verify(this)) {
2966       tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", p2i(this));
2967     }
2968   }
2969 
2970 #ifdef ASSERT
2971 #if INCLUDE_JVMCI
2972   {
2973     // Verify that implicit exceptions that deoptimize have a PcDesc and OopMap
2974     ImmutableOopMapSet* oms = oop_maps();
2975     ImplicitExceptionTable implicit_table(this);
2976     for (uint i = 0; i < implicit_table.len(); i++) {
2977       int exec_offset = (int) implicit_table.get_exec_offset(i);
2978       if (implicit_table.get_exec_offset(i) == implicit_table.get_cont_offset(i)) {
2979         assert(pc_desc_at(code_begin() + exec_offset) != nullptr, "missing PcDesc");
2980         bool found = false;
2981         for (int i = 0, imax = oms->count(); i < imax; i++) {
2982           if (oms->pair_at(i)->pc_offset() == exec_offset) {
2983             found = true;
2984             break;
2985           }
2986         }
2987         assert(found, "missing oopmap");
2988       }
2989     }
2990   }
2991 #endif
2992 #endif
2993 
2994   VerifyOopsClosure voc(this);
2995   oops_do(&voc);
2996   assert(voc.ok(), "embedded oops must be OK");
2997   Universe::heap()->verify_nmethod(this);
2998 
2999   assert(_oops_do_mark_link == nullptr, "_oops_do_mark_link for %s should be nullptr but is " PTR_FORMAT,
3000          nm->method()->external_name(), p2i(_oops_do_mark_link));
3001   verify_scopes();
3002 
3003   CompiledICLocker nm_verify(this);
3004   VerifyMetadataClosure vmc;
3005   metadata_do(&vmc);
3006 }
3007 
3008 
3009 void nmethod::verify_interrupt_point(address call_site, bool is_inline_cache) {
3010 
3011   // Verify IC only when nmethod installation is finished.
3012   if (!is_not_installed()) {
3013     if (CompiledICLocker::is_safe(this)) {
3014       if (is_inline_cache) {
3015         CompiledIC_at(this, call_site);
3016       } else {
3017         CompiledDirectCall::at(call_site);
3018       }
3019     } else {
3020       CompiledICLocker ml_verify(this);
3021       if (is_inline_cache) {
3022         CompiledIC_at(this, call_site);
3023       } else {
3024         CompiledDirectCall::at(call_site);
3025       }
3026     }
3027   }
3028 
3029   HandleMark hm(Thread::current());
3030 
3031   PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address());
3032   assert(pd != nullptr, "PcDesc must exist");
3033   for (ScopeDesc* sd = new ScopeDesc(this, pd);
3034        !sd->is_top(); sd = sd->sender()) {
3035     sd->verify();
3036   }
3037 }
3038 
3039 void nmethod::verify_scopes() {
3040   if( !method() ) return;       // Runtime stubs have no scope
3041   if (method()->is_native()) return; // Ignore stub methods.
3042   // iterate through all interrupt point
3043   // and verify the debug information is valid.
3044   RelocIterator iter(this);
3045   while (iter.next()) {
3046     address stub = nullptr;
3047     switch (iter.type()) {
3048       case relocInfo::virtual_call_type:
3049         verify_interrupt_point(iter.addr(), true /* is_inline_cache */);
3050         break;
3051       case relocInfo::opt_virtual_call_type:
3052         stub = iter.opt_virtual_call_reloc()->static_stub();
3053         verify_interrupt_point(iter.addr(), false /* is_inline_cache */);
3054         break;
3055       case relocInfo::static_call_type:
3056         stub = iter.static_call_reloc()->static_stub();
3057         verify_interrupt_point(iter.addr(), false /* is_inline_cache */);
3058         break;
3059       case relocInfo::runtime_call_type:
3060       case relocInfo::runtime_call_w_cp_type: {
3061         address destination = iter.reloc()->value();
3062         // Right now there is no way to find out which entries support
3063         // an interrupt point.  It would be nice if we had this
3064         // information in a table.
3065         break;
3066       }
3067       default:
3068         break;
3069     }
3070     assert(stub == nullptr || stub_contains(stub), "static call stub outside stub section");
3071   }
3072 }
3073 
3074 
3075 // -----------------------------------------------------------------------------
3076 // Printing operations
3077 
3078 void nmethod::print_on_impl(outputStream* st) const {
3079   ResourceMark rm;
3080 
3081   st->print("Compiled method ");
3082 
3083   if (is_compiled_by_c1()) {
3084     st->print("(c1) ");
3085   } else if (is_compiled_by_c2()) {
3086     st->print("(c2) ");
3087   } else if (is_compiled_by_jvmci()) {
3088     st->print("(JVMCI) ");
3089   } else {
3090     st->print("(n/a) ");
3091   }
3092 
3093   print_on_with_msg(st, nullptr);
3094 
3095   if (WizardMode) {
3096     st->print("((nmethod*) " INTPTR_FORMAT ") ", p2i(this));
3097     st->print(" for method " INTPTR_FORMAT , p2i(method()));
3098     st->print(" { ");
3099     st->print_cr("%s ", state());
3100     st->print_cr("}:");
3101   }
3102   if (size              () > 0) st->print_cr(" total in heap  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3103                                              p2i(this),
3104                                              p2i(this) + size(),
3105                                              size());
3106   if (consts_size       () > 0) st->print_cr(" constants      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3107                                              p2i(consts_begin()),
3108                                              p2i(consts_end()),
3109                                              consts_size());
3110   if (insts_size        () > 0) st->print_cr(" main code      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3111                                              p2i(insts_begin()),
3112                                              p2i(insts_end()),
3113                                              insts_size());
3114   if (stub_size         () > 0) st->print_cr(" stub code      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3115                                              p2i(stub_begin()),
3116                                              p2i(stub_end()),
3117                                              stub_size());
3118   if (oops_size         () > 0) st->print_cr(" oops           [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3119                                              p2i(oops_begin()),
3120                                              p2i(oops_end()),
3121                                              oops_size());
3122   if (mutable_data_size() > 0) st->print_cr(" mutable data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3123                                              p2i(mutable_data_begin()),
3124                                              p2i(mutable_data_end()),
3125                                              mutable_data_size());
3126   if (relocation_size() > 0)   st->print_cr(" relocation     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3127                                              p2i(relocation_begin()),
3128                                              p2i(relocation_end()),
3129                                              relocation_size());
3130   if (metadata_size     () > 0) st->print_cr(" metadata       [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3131                                              p2i(metadata_begin()),
3132                                              p2i(metadata_end()),
3133                                              metadata_size());
3134 #if INCLUDE_JVMCI
3135   if (jvmci_data_size   () > 0) st->print_cr(" JVMCI data     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3136                                              p2i(jvmci_data_begin()),
3137                                              p2i(jvmci_data_end()),
3138                                              jvmci_data_size());
3139 #endif
3140   if (immutable_data_size() > 0) st->print_cr(" immutable data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3141                                              p2i(immutable_data_begin()),
3142                                              p2i(immutable_data_end()),
3143                                              immutable_data_size());
3144   if (dependencies_size () > 0) st->print_cr(" dependencies   [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3145                                              p2i(dependencies_begin()),
3146                                              p2i(dependencies_end()),
3147                                              dependencies_size());
3148   if (nul_chk_table_size() > 0) st->print_cr(" nul chk table  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3149                                              p2i(nul_chk_table_begin()),
3150                                              p2i(nul_chk_table_end()),
3151                                              nul_chk_table_size());
3152   if (handler_table_size() > 0) st->print_cr(" handler table  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3153                                              p2i(handler_table_begin()),
3154                                              p2i(handler_table_end()),
3155                                              handler_table_size());
3156   if (scopes_pcs_size   () > 0) st->print_cr(" scopes pcs     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3157                                              p2i(scopes_pcs_begin()),
3158                                              p2i(scopes_pcs_end()),
3159                                              scopes_pcs_size());
3160   if (scopes_data_size  () > 0) st->print_cr(" scopes data    [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3161                                              p2i(scopes_data_begin()),
3162                                              p2i(scopes_data_end()),
3163                                              scopes_data_size());
3164 #if INCLUDE_JVMCI
3165   if (speculations_size () > 0) st->print_cr(" speculations   [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3166                                              p2i(speculations_begin()),
3167                                              p2i(speculations_end()),
3168                                              speculations_size());
3169 #endif
3170 }
3171 
3172 void nmethod::print_code() {
3173   ResourceMark m;
3174   ttyLocker ttyl;
3175   // Call the specialized decode method of this class.
3176   decode(tty);
3177 }
3178 
3179 #ifndef PRODUCT  // called InstanceKlass methods are available only then. Declared as PRODUCT_RETURN
3180 
3181 void nmethod::print_dependencies_on(outputStream* out) {
3182   ResourceMark rm;
3183   stringStream st;
3184   st.print_cr("Dependencies:");
3185   for (Dependencies::DepStream deps(this); deps.next(); ) {
3186     deps.print_dependency(&st);
3187     InstanceKlass* ctxk = deps.context_type();
3188     if (ctxk != nullptr) {
3189       if (ctxk->is_dependent_nmethod(this)) {
3190         st.print_cr("   [nmethod<=klass]%s", ctxk->external_name());
3191       }
3192     }
3193     deps.log_dependency();  // put it into the xml log also
3194   }
3195   out->print_raw(st.as_string());
3196 }
3197 #endif
3198 
3199 #if defined(SUPPORT_DATA_STRUCTS)
3200 
3201 // Print the oops from the underlying CodeBlob.
3202 void nmethod::print_oops(outputStream* st) {
3203   ResourceMark m;
3204   st->print("Oops:");
3205   if (oops_begin() < oops_end()) {
3206     st->cr();
3207     for (oop* p = oops_begin(); p < oops_end(); p++) {
3208       Disassembler::print_location((unsigned char*)p, (unsigned char*)oops_begin(), (unsigned char*)oops_end(), st, true, false);
3209       st->print(PTR_FORMAT " ", *((uintptr_t*)p));
3210       if (Universe::contains_non_oop_word(p)) {
3211         st->print_cr("NON_OOP");
3212         continue;  // skip non-oops
3213       }
3214       if (*p == nullptr) {
3215         st->print_cr("nullptr-oop");
3216         continue;  // skip non-oops
3217       }
3218       (*p)->print_value_on(st);
3219       st->cr();
3220     }
3221   } else {
3222     st->print_cr(" <list empty>");
3223   }
3224 }
3225 
3226 // Print metadata pool.
3227 void nmethod::print_metadata(outputStream* st) {
3228   ResourceMark m;
3229   st->print("Metadata:");
3230   if (metadata_begin() < metadata_end()) {
3231     st->cr();
3232     for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
3233       Disassembler::print_location((unsigned char*)p, (unsigned char*)metadata_begin(), (unsigned char*)metadata_end(), st, true, false);
3234       st->print(PTR_FORMAT " ", *((uintptr_t*)p));
3235       if (*p && *p != Universe::non_oop_word()) {
3236         (*p)->print_value_on(st);
3237       }
3238       st->cr();
3239     }
3240   } else {
3241     st->print_cr(" <list empty>");
3242   }
3243 }
3244 
3245 #ifndef PRODUCT  // ScopeDesc::print_on() is available only then. Declared as PRODUCT_RETURN
3246 void nmethod::print_scopes_on(outputStream* st) {
3247   // Find the first pc desc for all scopes in the code and print it.
3248   ResourceMark rm;
3249   st->print("scopes:");
3250   if (scopes_pcs_begin() < scopes_pcs_end()) {
3251     st->cr();
3252     for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3253       if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null)
3254         continue;
3255 
3256       ScopeDesc* sd = scope_desc_at(p->real_pc(this));
3257       while (sd != nullptr) {
3258         sd->print_on(st, p);  // print output ends with a newline
3259         sd = sd->sender();
3260       }
3261     }
3262   } else {
3263     st->print_cr(" <list empty>");
3264   }
3265 }
3266 #endif
3267 
3268 #ifndef PRODUCT  // RelocIterator does support printing only then.
3269 void nmethod::print_relocations() {
3270   ResourceMark m;       // in case methods get printed via the debugger
3271   tty->print_cr("relocations:");
3272   RelocIterator iter(this);
3273   iter.print_on(tty);
3274 }
3275 #endif
3276 
3277 void nmethod::print_pcs_on(outputStream* st) {
3278   ResourceMark m;       // in case methods get printed via debugger
3279   st->print("pc-bytecode offsets:");
3280   if (scopes_pcs_begin() < scopes_pcs_end()) {
3281     st->cr();
3282     for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3283       p->print_on(st, this);  // print output ends with a newline
3284     }
3285   } else {
3286     st->print_cr(" <list empty>");
3287   }
3288 }
3289 
3290 void nmethod::print_handler_table() {
3291   ExceptionHandlerTable(this).print(code_begin());
3292 }
3293 
3294 void nmethod::print_nul_chk_table() {
3295   ImplicitExceptionTable(this).print(code_begin());
3296 }
3297 
3298 void nmethod::print_recorded_oop(int log_n, int i) {
3299   void* value;
3300 
3301   if (i == 0) {
3302     value = nullptr;
3303   } else {
3304     // Be careful around non-oop words. Don't create an oop
3305     // with that value, or it will assert in verification code.
3306     if (Universe::contains_non_oop_word(oop_addr_at(i))) {
3307       value = Universe::non_oop_word();
3308     } else {
3309       value = oop_at(i);
3310     }
3311   }
3312 
3313   tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(value));
3314 
3315   if (value == Universe::non_oop_word()) {
3316     tty->print("non-oop word");
3317   } else {
3318     if (value == nullptr) {
3319       tty->print("nullptr-oop");
3320     } else {
3321       oop_at(i)->print_value_on(tty);
3322     }
3323   }
3324 
3325   tty->cr();
3326 }
3327 
3328 void nmethod::print_recorded_oops() {
3329   const int n = oops_count();
3330   const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6;
3331   tty->print("Recorded oops:");
3332   if (n > 0) {
3333     tty->cr();
3334     for (int i = 0; i < n; i++) {
3335       print_recorded_oop(log_n, i);
3336     }
3337   } else {
3338     tty->print_cr(" <list empty>");
3339   }
3340 }
3341 
3342 void nmethod::print_recorded_metadata() {
3343   const int n = metadata_count();
3344   const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6;
3345   tty->print("Recorded metadata:");
3346   if (n > 0) {
3347     tty->cr();
3348     for (int i = 0; i < n; i++) {
3349       Metadata* m = metadata_at(i);
3350       tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(m));
3351       if (m == (Metadata*)Universe::non_oop_word()) {
3352         tty->print("non-metadata word");
3353       } else if (m == nullptr) {
3354         tty->print("nullptr-oop");
3355       } else {
3356         Metadata::print_value_on_maybe_null(tty, m);
3357       }
3358       tty->cr();
3359     }
3360   } else {
3361     tty->print_cr(" <list empty>");
3362   }
3363 }
3364 #endif
3365 
3366 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
3367 
3368 void nmethod::print_constant_pool(outputStream* st) {
3369   //-----------------------------------
3370   //---<  Print the constant pool  >---
3371   //-----------------------------------
3372   int consts_size = this->consts_size();
3373   if ( consts_size > 0 ) {
3374     unsigned char* cstart = this->consts_begin();
3375     unsigned char* cp     = cstart;
3376     unsigned char* cend   = cp + consts_size;
3377     unsigned int   bytes_per_line = 4;
3378     unsigned int   CP_alignment   = 8;
3379     unsigned int   n;
3380 
3381     st->cr();
3382 
3383     //---<  print CP header to make clear what's printed  >---
3384     if( ((uintptr_t)cp&(CP_alignment-1)) == 0 ) {
3385       n = bytes_per_line;
3386       st->print_cr("[Constant Pool]");
3387       Disassembler::print_location(cp, cstart, cend, st, true, true);
3388       Disassembler::print_hexdata(cp, n, st, true);
3389       st->cr();
3390     } else {
3391       n = (int)((uintptr_t)cp & (bytes_per_line-1));
3392       st->print_cr("[Constant Pool (unaligned)]");
3393     }
3394 
3395     //---<  print CP contents, bytes_per_line at a time  >---
3396     while (cp < cend) {
3397       Disassembler::print_location(cp, cstart, cend, st, true, false);
3398       Disassembler::print_hexdata(cp, n, st, false);
3399       cp += n;
3400       n   = bytes_per_line;
3401       st->cr();
3402     }
3403 
3404     //---<  Show potential alignment gap between constant pool and code  >---
3405     cend = code_begin();
3406     if( cp < cend ) {
3407       n = 4;
3408       st->print_cr("[Code entry alignment]");
3409       while (cp < cend) {
3410         Disassembler::print_location(cp, cstart, cend, st, false, false);
3411         cp += n;
3412         st->cr();
3413       }
3414     }
3415   } else {
3416     st->print_cr("[Constant Pool (empty)]");
3417   }
3418   st->cr();
3419 }
3420 
3421 #endif
3422 
3423 // Disassemble this nmethod.
3424 // Print additional debug information, if requested. This could be code
3425 // comments, block comments, profiling counters, etc.
3426 // The undisassembled format is useful no disassembler library is available.
3427 // The resulting hex dump (with markers) can be disassembled later, or on
3428 // another system, when/where a disassembler library is available.
3429 void nmethod::decode2(outputStream* ost) const {
3430 
3431   // Called from frame::back_trace_with_decode without ResourceMark.
3432   ResourceMark rm;
3433 
3434   // Make sure we have a valid stream to print on.
3435   outputStream* st = ost ? ost : tty;
3436 
3437 #if defined(SUPPORT_ABSTRACT_ASSEMBLY) && ! defined(SUPPORT_ASSEMBLY)
3438   const bool use_compressed_format    = true;
3439   const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() ||
3440                                                                   AbstractDisassembler::show_block_comment());
3441 #else
3442   const bool use_compressed_format    = Disassembler::is_abstract();
3443   const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() ||
3444                                                                   AbstractDisassembler::show_block_comment());
3445 #endif
3446 
3447   st->cr();
3448   this->print_on(st);
3449   st->cr();
3450 
3451 #if defined(SUPPORT_ASSEMBLY)
3452   //----------------------------------
3453   //---<  Print real disassembly  >---
3454   //----------------------------------
3455   if (! use_compressed_format) {
3456     st->print_cr("[Disassembly]");
3457     Disassembler::decode(const_cast<nmethod*>(this), st);
3458     st->bol();
3459     st->print_cr("[/Disassembly]");
3460     return;
3461   }
3462 #endif
3463 
3464 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
3465 
3466   // Compressed undisassembled disassembly format.
3467   // The following status values are defined/supported:
3468   //   = 0 - currently at bol() position, nothing printed yet on current line.
3469   //   = 1 - currently at position after print_location().
3470   //   > 1 - in the midst of printing instruction stream bytes.
3471   int        compressed_format_idx    = 0;
3472   int        code_comment_column      = 0;
3473   const int  instr_maxlen             = Assembler::instr_maxlen();
3474   const uint tabspacing               = 8;
3475   unsigned char* start = this->code_begin();
3476   unsigned char* p     = this->code_begin();
3477   unsigned char* end   = this->code_end();
3478   unsigned char* pss   = p; // start of a code section (used for offsets)
3479 
3480   if ((start == nullptr) || (end == nullptr)) {
3481     st->print_cr("PrintAssembly not possible due to uninitialized section pointers");
3482     return;
3483   }
3484 #endif
3485 
3486 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
3487   //---<  plain abstract disassembly, no comments or anything, just section headers  >---
3488   if (use_compressed_format && ! compressed_with_comments) {
3489     const_cast<nmethod*>(this)->print_constant_pool(st);
3490 
3491     st->bol();
3492     st->cr();
3493     st->print_cr("Loading hsdis library failed, undisassembled code is shown in MachCode section");
3494     //---<  Open the output (Marker for post-mortem disassembler)  >---
3495     st->print_cr("[MachCode]");
3496     const char* header = nullptr;
3497     address p0 = p;
3498     while (p < end) {
3499       address pp = p;
3500       while ((p < end) && (header == nullptr)) {
3501         header = nmethod_section_label(p);
3502         pp  = p;
3503         p  += Assembler::instr_len(p);
3504       }
3505       if (pp > p0) {
3506         AbstractDisassembler::decode_range_abstract(p0, pp, start, end, st, Assembler::instr_maxlen());
3507         p0 = pp;
3508         p  = pp;
3509         header = nullptr;
3510       } else if (header != nullptr) {
3511         st->bol();
3512         st->print_cr("%s", header);
3513         header = nullptr;
3514       }
3515     }
3516     //---<  Close the output (Marker for post-mortem disassembler)  >---
3517     st->bol();
3518     st->print_cr("[/MachCode]");
3519     return;
3520   }
3521 #endif
3522 
3523 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
3524   //---<  abstract disassembly with comments and section headers merged in  >---
3525   if (compressed_with_comments) {
3526     const_cast<nmethod*>(this)->print_constant_pool(st);
3527 
3528     st->bol();
3529     st->cr();
3530     st->print_cr("Loading hsdis library failed, undisassembled code is shown in MachCode section");
3531     //---<  Open the output (Marker for post-mortem disassembler)  >---
3532     st->print_cr("[MachCode]");
3533     while ((p < end) && (p != nullptr)) {
3534       const int instruction_size_in_bytes = Assembler::instr_len(p);
3535 
3536       //---<  Block comments for nmethod. Interrupts instruction stream, if any.  >---
3537       // Outputs a bol() before and a cr() after, but only if a comment is printed.
3538       // Prints nmethod_section_label as well.
3539       if (AbstractDisassembler::show_block_comment()) {
3540         print_block_comment(st, p);
3541         if (st->position() == 0) {
3542           compressed_format_idx = 0;
3543         }
3544       }
3545 
3546       //---<  New location information after line break  >---
3547       if (compressed_format_idx == 0) {
3548         code_comment_column   = Disassembler::print_location(p, pss, end, st, false, false);
3549         compressed_format_idx = 1;
3550       }
3551 
3552       //---<  Code comment for current instruction. Address range [p..(p+len))  >---
3553       unsigned char* p_end = p + (ssize_t)instruction_size_in_bytes;
3554       S390_ONLY(if (p_end > end) p_end = end;) // avoid getting past the end
3555 
3556       if (AbstractDisassembler::show_comment() && const_cast<nmethod*>(this)->has_code_comment(p, p_end)) {
3557         //---<  interrupt instruction byte stream for code comment  >---
3558         if (compressed_format_idx > 1) {
3559           st->cr();  // interrupt byte stream
3560           st->cr();  // add an empty line
3561           code_comment_column = Disassembler::print_location(p, pss, end, st, false, false);
3562         }
3563         const_cast<nmethod*>(this)->print_code_comment_on(st, code_comment_column, p, p_end );
3564         st->bol();
3565         compressed_format_idx = 0;
3566       }
3567 
3568       //---<  New location information after line break  >---
3569       if (compressed_format_idx == 0) {
3570         code_comment_column   = Disassembler::print_location(p, pss, end, st, false, false);
3571         compressed_format_idx = 1;
3572       }
3573 
3574       //---<  Nicely align instructions for readability  >---
3575       if (compressed_format_idx > 1) {
3576         Disassembler::print_delimiter(st);
3577       }
3578 
3579       //---<  Now, finally, print the actual instruction bytes  >---
3580       unsigned char* p0 = p;
3581       p = Disassembler::decode_instruction_abstract(p, st, instruction_size_in_bytes, instr_maxlen);
3582       compressed_format_idx += (int)(p - p0);
3583 
3584       if (Disassembler::start_newline(compressed_format_idx-1)) {
3585         st->cr();
3586         compressed_format_idx = 0;
3587       }
3588     }
3589     //---<  Close the output (Marker for post-mortem disassembler)  >---
3590     st->bol();
3591     st->print_cr("[/MachCode]");
3592     return;
3593   }
3594 #endif
3595 }
3596 
3597 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
3598 
3599 const char* nmethod::reloc_string_for(u_char* begin, u_char* end) {
3600   RelocIterator iter(this, begin, end);
3601   bool have_one = false;
3602   while (iter.next()) {
3603     have_one = true;
3604     switch (iter.type()) {
3605         case relocInfo::none: {
3606           // Skip it and check next
3607           break;
3608         }
3609         case relocInfo::oop_type: {
3610           // Get a non-resizable resource-allocated stringStream.
3611           // Our callees make use of (nested) ResourceMarks.
3612           stringStream st(NEW_RESOURCE_ARRAY(char, 1024), 1024);
3613           oop_Relocation* r = iter.oop_reloc();
3614           oop obj = r->oop_value();
3615           st.print("oop(");
3616           if (obj == nullptr) st.print("nullptr");
3617           else obj->print_value_on(&st);
3618           st.print(")");
3619           return st.as_string();
3620         }
3621         case relocInfo::metadata_type: {
3622           stringStream st;
3623           metadata_Relocation* r = iter.metadata_reloc();
3624           Metadata* obj = r->metadata_value();
3625           st.print("metadata(");
3626           if (obj == nullptr) st.print("nullptr");
3627           else obj->print_value_on(&st);
3628           st.print(")");
3629           return st.as_string();
3630         }
3631         case relocInfo::runtime_call_type:
3632         case relocInfo::runtime_call_w_cp_type: {
3633           stringStream st;
3634           st.print("runtime_call");
3635           CallRelocation* r = (CallRelocation*)iter.reloc();
3636           address dest = r->destination();
3637           if (StubRoutines::contains(dest)) {
3638             StubCodeDesc* desc = StubCodeDesc::desc_for(dest);
3639             if (desc == nullptr) {
3640               desc = StubCodeDesc::desc_for(dest + frame::pc_return_offset);
3641             }
3642             if (desc != nullptr) {
3643               st.print(" Stub::%s", desc->name());
3644               return st.as_string();
3645             }
3646           }
3647           CodeBlob* cb = CodeCache::find_blob(dest);
3648           if (cb != nullptr) {
3649             st.print(" %s", cb->name());
3650           } else {
3651             ResourceMark rm;
3652             const int buflen = 1024;
3653             char* buf = NEW_RESOURCE_ARRAY(char, buflen);
3654             int offset;
3655             if (os::dll_address_to_function_name(dest, buf, buflen, &offset)) {
3656               st.print(" %s", buf);
3657               if (offset != 0) {
3658                 st.print("+%d", offset);
3659               }
3660             }
3661           }
3662           return st.as_string();
3663         }
3664         case relocInfo::virtual_call_type: {
3665           stringStream st;
3666           st.print_raw("virtual_call");
3667           virtual_call_Relocation* r = iter.virtual_call_reloc();
3668           Method* m = r->method_value();
3669           if (m != nullptr) {
3670             assert(m->is_method(), "");
3671             m->print_short_name(&st);
3672           }
3673           return st.as_string();
3674         }
3675         case relocInfo::opt_virtual_call_type: {
3676           stringStream st;
3677           st.print_raw("optimized virtual_call");
3678           opt_virtual_call_Relocation* r = iter.opt_virtual_call_reloc();
3679           Method* m = r->method_value();
3680           if (m != nullptr) {
3681             assert(m->is_method(), "");
3682             m->print_short_name(&st);
3683           }
3684           return st.as_string();
3685         }
3686         case relocInfo::static_call_type: {
3687           stringStream st;
3688           st.print_raw("static_call");
3689           static_call_Relocation* r = iter.static_call_reloc();
3690           Method* m = r->method_value();
3691           if (m != nullptr) {
3692             assert(m->is_method(), "");
3693             m->print_short_name(&st);
3694           }
3695           return st.as_string();
3696         }
3697         case relocInfo::static_stub_type:      return "static_stub";
3698         case relocInfo::external_word_type:    return "external_word";
3699         case relocInfo::internal_word_type:    return "internal_word";
3700         case relocInfo::section_word_type:     return "section_word";
3701         case relocInfo::poll_type:             return "poll";
3702         case relocInfo::poll_return_type:      return "poll_return";
3703         case relocInfo::trampoline_stub_type:  return "trampoline_stub";
3704         case relocInfo::entry_guard_type:      return "entry_guard";
3705         case relocInfo::post_call_nop_type:    return "post_call_nop";
3706         case relocInfo::barrier_type: {
3707           barrier_Relocation* const reloc = iter.barrier_reloc();
3708           stringStream st;
3709           st.print("barrier format=%d", reloc->format());
3710           return st.as_string();
3711         }
3712 
3713         case relocInfo::type_mask:             return "type_bit_mask";
3714 
3715         default: {
3716           stringStream st;
3717           st.print("unknown relocInfo=%d", (int) iter.type());
3718           return st.as_string();
3719         }
3720     }
3721   }
3722   return have_one ? "other" : nullptr;
3723 }
3724 
3725 // Return the last scope in (begin..end]
3726 ScopeDesc* nmethod::scope_desc_in(address begin, address end) {
3727   PcDesc* p = pc_desc_near(begin+1);
3728   if (p != nullptr && p->real_pc(this) <= end) {
3729     return new ScopeDesc(this, p);
3730   }
3731   return nullptr;
3732 }
3733 
3734 const char* nmethod::nmethod_section_label(address pos) const {
3735   const char* label = nullptr;
3736   if (pos == code_begin())                                              label = "[Instructions begin]";
3737   if (pos == entry_point())                                             label = "[Entry Point]";
3738   if (pos == inline_entry_point())                                      label = "[Inline Entry Point]";
3739   if (pos == verified_entry_point())                                    label = "[Verified Entry Point]";
3740   if (pos == verified_inline_entry_point())                             label = "[Verified Inline Entry Point]";
3741   if (pos == verified_inline_ro_entry_point())                          label = "[Verified Inline Entry Point (RO)]";
3742   if (has_method_handle_invokes() && (pos == deopt_mh_handler_begin())) label = "[Deopt MH Handler Code]";
3743   if (pos == consts_begin() && pos != insts_begin())                    label = "[Constants]";
3744   // Check stub_code before checking exception_handler or deopt_handler.
3745   if (pos == this->stub_begin())                                        label = "[Stub Code]";
3746   if (JVMCI_ONLY(_exception_offset >= 0 &&) pos == exception_begin())          label = "[Exception Handler]";
3747   if (JVMCI_ONLY(_deopt_handler_offset != -1 &&) pos == deopt_handler_begin()) label = "[Deopt Handler Code]";
3748   return label;
3749 }
3750 
3751 static int maybe_print_entry_label(outputStream* stream, address pos, address entry, const char* label) {
3752   if (pos == entry) {
3753     stream->bol();
3754     stream->print_cr("%s", label);
3755     return 1;
3756   } else {
3757     return 0;
3758   }
3759 }
3760 
3761 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin, bool print_section_labels) const {
3762   if (print_section_labels) {
3763     int n = 0;
3764     // Multiple entry points may be at the same position. Print them all.
3765     n += maybe_print_entry_label(stream, block_begin, entry_point(),                    "[Entry Point]");
3766     n += maybe_print_entry_label(stream, block_begin, inline_entry_point(),             "[Inline Entry Point]");
3767     n += maybe_print_entry_label(stream, block_begin, verified_entry_point(),           "[Verified Entry Point]");
3768     n += maybe_print_entry_label(stream, block_begin, verified_inline_entry_point(),    "[Verified Inline Entry Point]");
3769     n += maybe_print_entry_label(stream, block_begin, verified_inline_ro_entry_point(), "[Verified Inline Entry Point (RO)]");
3770     if (n == 0) {
3771       const char* label = nmethod_section_label(block_begin);
3772       if (label != nullptr) {
3773         stream->bol();
3774         stream->print_cr("%s", label);
3775       }
3776     }
3777   }
3778 
3779   Method* m = method();
3780   if (m == nullptr || is_osr_method()) {
3781     return;
3782   }
3783 
3784   // Print the name of the method (only once)
3785   address low = MIN3(entry_point(),
3786                      verified_entry_point(),
3787                      inline_entry_point());
3788   // The verified inline entry point and verified inline RO entry point are not always
3789   // used. When they are unused. CodeOffsets::Verified_Inline_Entry(_RO) is -1. Hence,
3790   // the calculated entry point is smaller than the block they are offsetting into.
3791   if (verified_inline_entry_point() >= block_begin) {
3792     low = MIN2(low, verified_inline_entry_point());
3793   }
3794   if (verified_inline_ro_entry_point() >= block_begin) {
3795     low = MIN2(low, verified_inline_ro_entry_point());
3796   }
3797   assert(low != 0, "sanity");
3798   if (block_begin == low) {
3799     stream->print("  # ");
3800     m->print_value_on(stream);
3801     stream->cr();
3802   }
3803 
3804   // Print the arguments for the 3 types of verified entry points
3805   CompiledEntrySignature ces(m);
3806   ces.compute_calling_conventions(false);
3807   const GrowableArray<SigEntry>* sig_cc;
3808   const VMRegPair* regs;
3809   if (block_begin == verified_entry_point()) {
3810     sig_cc = ces.sig_cc();
3811     regs = ces.regs_cc();
3812   } else if (block_begin == verified_inline_entry_point()) {
3813     sig_cc = ces.sig();
3814     regs = ces.regs();
3815   } else if (block_begin == verified_inline_ro_entry_point()) {
3816     sig_cc = ces.sig_cc_ro();
3817     regs = ces.regs_cc_ro();
3818   } else {
3819     return;
3820   }
3821 
3822   bool has_this = !m->is_static();
3823   if (ces.has_inline_recv() && block_begin == verified_entry_point()) {
3824     // <this> argument is scalarized for verified_entry_point()
3825     has_this = false;
3826   }
3827   const char* spname = "sp"; // make arch-specific?
3828   int stack_slot_offset = this->frame_size() * wordSize;
3829   int tab1 = 14, tab2 = 24;
3830   int sig_index = 0;
3831   int arg_index = has_this ? -1 : 0;
3832   bool did_old_sp = false;
3833   for (ExtendedSignature sig = ExtendedSignature(sig_cc, SigEntryFilter()); !sig.at_end(); ++sig) {
3834     bool at_this = (arg_index == -1);
3835     bool at_old_sp = false;
3836     BasicType t = (*sig)._bt;
3837     if (at_this) {
3838       stream->print("  # this: ");
3839     } else {
3840       stream->print("  # parm%d: ", arg_index);
3841     }
3842     stream->move_to(tab1);
3843     VMReg fst = regs[sig_index].first();
3844     VMReg snd = regs[sig_index].second();
3845     if (fst->is_reg()) {
3846       stream->print("%s", fst->name());
3847       if (snd->is_valid())  {
3848         stream->print(":%s", snd->name());
3849       }
3850     } else if (fst->is_stack()) {
3851       int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset;
3852       if (offset == stack_slot_offset)  at_old_sp = true;
3853       stream->print("[%s+0x%x]", spname, offset);
3854     } else {
3855       stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd);
3856     }
3857     stream->print(" ");
3858     stream->move_to(tab2);
3859     stream->print("= ");
3860     if (at_this) {
3861       m->method_holder()->print_value_on(stream);
3862     } else {
3863       bool did_name = false;
3864       if (is_reference_type(t)) {
3865         Symbol* name = (*sig)._name;
3866         name->print_value_on(stream);
3867         did_name = true;
3868       }
3869       if (!did_name)
3870         stream->print("%s", type2name(t));
3871       if ((*sig)._null_marker) {
3872         stream->print(" (null marker)");
3873       }
3874     }
3875     if (at_old_sp) {
3876       stream->print("  (%s of caller)", spname);
3877       did_old_sp = true;
3878     }
3879     stream->cr();
3880     sig_index += type2size[t];
3881     arg_index += 1;
3882   }
3883   if (!did_old_sp) {
3884     stream->print("  # ");
3885     stream->move_to(tab1);
3886     stream->print("[%s+0x%x]", spname, stack_slot_offset);
3887     stream->print("  (%s of caller)", spname);
3888     stream->cr();
3889   }
3890 }
3891 
3892 // Returns whether this nmethod has code comments.
3893 bool nmethod::has_code_comment(address begin, address end) {
3894   // scopes?
3895   ScopeDesc* sd  = scope_desc_in(begin, end);
3896   if (sd != nullptr) return true;
3897 
3898   // relocations?
3899   const char* str = reloc_string_for(begin, end);
3900   if (str != nullptr) return true;
3901 
3902   // implicit exceptions?
3903   int cont_offset = ImplicitExceptionTable(this).continuation_offset((uint)(begin - code_begin()));
3904   if (cont_offset != 0) return true;
3905 
3906   return false;
3907 }
3908 
3909 void nmethod::print_code_comment_on(outputStream* st, int column, address begin, address end) {
3910   ImplicitExceptionTable implicit_table(this);
3911   int pc_offset = (int)(begin - code_begin());
3912   int cont_offset = implicit_table.continuation_offset(pc_offset);
3913   bool oop_map_required = false;
3914   if (cont_offset != 0) {
3915     st->move_to(column, 6, 0);
3916     if (pc_offset == cont_offset) {
3917       st->print("; implicit exception: deoptimizes");
3918       oop_map_required = true;
3919     } else {
3920       st->print("; implicit exception: dispatches to " INTPTR_FORMAT, p2i(code_begin() + cont_offset));
3921     }
3922   }
3923 
3924   // Find an oopmap in (begin, end].  We use the odd half-closed
3925   // interval so that oop maps and scope descs which are tied to the
3926   // byte after a call are printed with the call itself.  OopMaps
3927   // associated with implicit exceptions are printed with the implicit
3928   // instruction.
3929   address base = code_begin();
3930   ImmutableOopMapSet* oms = oop_maps();
3931   if (oms != nullptr) {
3932     for (int i = 0, imax = oms->count(); i < imax; i++) {
3933       const ImmutableOopMapPair* pair = oms->pair_at(i);
3934       const ImmutableOopMap* om = pair->get_from(oms);
3935       address pc = base + pair->pc_offset();
3936       if (pc >= begin) {
3937 #if INCLUDE_JVMCI
3938         bool is_implicit_deopt = implicit_table.continuation_offset(pair->pc_offset()) == (uint) pair->pc_offset();
3939 #else
3940         bool is_implicit_deopt = false;
3941 #endif
3942         if (is_implicit_deopt ? pc == begin : pc > begin && pc <= end) {
3943           st->move_to(column, 6, 0);
3944           st->print("; ");
3945           om->print_on(st);
3946           oop_map_required = false;
3947         }
3948       }
3949       if (pc > end) {
3950         break;
3951       }
3952     }
3953   }
3954   assert(!oop_map_required, "missed oopmap");
3955 
3956   Thread* thread = Thread::current();
3957 
3958   // Print any debug info present at this pc.
3959   ScopeDesc* sd  = scope_desc_in(begin, end);
3960   if (sd != nullptr) {
3961     st->move_to(column, 6, 0);
3962     if (sd->bci() == SynchronizationEntryBCI) {
3963       st->print(";*synchronization entry");
3964     } else if (sd->bci() == AfterBci) {
3965       st->print(";* method exit (unlocked if synchronized)");
3966     } else if (sd->bci() == UnwindBci) {
3967       st->print(";* unwind (locked if synchronized)");
3968     } else if (sd->bci() == AfterExceptionBci) {
3969       st->print(";* unwind (unlocked if synchronized)");
3970     } else if (sd->bci() == UnknownBci) {
3971       st->print(";* unknown");
3972     } else if (sd->bci() == InvalidFrameStateBci) {
3973       st->print(";* invalid frame state");
3974     } else {
3975       if (sd->method() == nullptr) {
3976         st->print("method is nullptr");
3977       } else if (sd->method()->is_native()) {
3978         st->print("method is native");
3979       } else {
3980         Bytecodes::Code bc = sd->method()->java_code_at(sd->bci());
3981         st->print(";*%s", Bytecodes::name(bc));
3982         switch (bc) {
3983         case Bytecodes::_invokevirtual:
3984         case Bytecodes::_invokespecial:
3985         case Bytecodes::_invokestatic:
3986         case Bytecodes::_invokeinterface:
3987           {
3988             Bytecode_invoke invoke(methodHandle(thread, sd->method()), sd->bci());
3989             st->print(" ");
3990             if (invoke.name() != nullptr)
3991               invoke.name()->print_symbol_on(st);
3992             else
3993               st->print("<UNKNOWN>");
3994             break;
3995           }
3996         case Bytecodes::_getfield:
3997         case Bytecodes::_putfield:
3998         case Bytecodes::_getstatic:
3999         case Bytecodes::_putstatic:
4000           {
4001             Bytecode_field field(methodHandle(thread, sd->method()), sd->bci());
4002             st->print(" ");
4003             if (field.name() != nullptr)
4004               field.name()->print_symbol_on(st);
4005             else
4006               st->print("<UNKNOWN>");
4007           }
4008         default:
4009           break;
4010         }
4011       }
4012       st->print(" {reexecute=%d rethrow=%d return_oop=%d return_scalarized=%d}", sd->should_reexecute(), sd->rethrow_exception(), sd->return_oop(), sd->return_scalarized());
4013     }
4014 
4015     // Print all scopes
4016     for (;sd != nullptr; sd = sd->sender()) {
4017       st->move_to(column, 6, 0);
4018       st->print("; -");
4019       if (sd->should_reexecute()) {
4020         st->print(" (reexecute)");
4021       }
4022       if (sd->method() == nullptr) {
4023         st->print("method is nullptr");
4024       } else {
4025         sd->method()->print_short_name(st);
4026       }
4027       int lineno = sd->method()->line_number_from_bci(sd->bci());
4028       if (lineno != -1) {
4029         st->print("@%d (line %d)", sd->bci(), lineno);
4030       } else {
4031         st->print("@%d", sd->bci());
4032       }
4033       st->cr();
4034     }
4035   }
4036 
4037   // Print relocation information
4038   // Prevent memory leak: allocating without ResourceMark.
4039   ResourceMark rm;
4040   const char* str = reloc_string_for(begin, end);
4041   if (str != nullptr) {
4042     if (sd != nullptr) st->cr();
4043     st->move_to(column, 6, 0);
4044     st->print(";   {%s}", str);
4045   }
4046 }
4047 
4048 #endif
4049 
4050 address nmethod::call_instruction_address(address pc) const {
4051   if (NativeCall::is_call_before(pc)) {
4052     NativeCall *ncall = nativeCall_before(pc);
4053     return ncall->instruction_address();
4054   }
4055   return nullptr;
4056 }
4057 
4058 void nmethod::print_value_on_impl(outputStream* st) const {
4059   st->print_cr("nmethod");
4060 #if defined(SUPPORT_DATA_STRUCTS)
4061   print_on_with_msg(st, nullptr);
4062 #endif
4063 }
4064 
4065 #ifndef PRODUCT
4066 
4067 void nmethod::print_calls(outputStream* st) {
4068   RelocIterator iter(this);
4069   while (iter.next()) {
4070     switch (iter.type()) {
4071     case relocInfo::virtual_call_type: {
4072       CompiledICLocker ml_verify(this);
4073       CompiledIC_at(&iter)->print();
4074       break;
4075     }
4076     case relocInfo::static_call_type:
4077     case relocInfo::opt_virtual_call_type:
4078       st->print_cr("Direct call at " INTPTR_FORMAT, p2i(iter.reloc()->addr()));
4079       CompiledDirectCall::at(iter.reloc())->print();
4080       break;
4081     default:
4082       break;
4083     }
4084   }
4085 }
4086 
4087 void nmethod::print_statistics() {
4088   ttyLocker ttyl;
4089   if (xtty != nullptr)  xtty->head("statistics type='nmethod'");
4090   native_nmethod_stats.print_native_nmethod_stats();
4091 #ifdef COMPILER1
4092   c1_java_nmethod_stats.print_nmethod_stats("C1");
4093 #endif
4094 #ifdef COMPILER2
4095   c2_java_nmethod_stats.print_nmethod_stats("C2");
4096 #endif
4097 #if INCLUDE_JVMCI
4098   jvmci_java_nmethod_stats.print_nmethod_stats("JVMCI");
4099 #endif
4100   unknown_java_nmethod_stats.print_nmethod_stats("Unknown");
4101   DebugInformationRecorder::print_statistics();
4102   pc_nmethod_stats.print_pc_stats();
4103   Dependencies::print_statistics();
4104   ExternalsRecorder::print_statistics();
4105   if (xtty != nullptr)  xtty->tail("statistics");
4106 }
4107 
4108 #endif // !PRODUCT
4109 
4110 #if INCLUDE_JVMCI
4111 void nmethod::update_speculation(JavaThread* thread) {
4112   jlong speculation = thread->pending_failed_speculation();
4113   if (speculation != 0) {
4114     guarantee(jvmci_nmethod_data() != nullptr, "failed speculation in nmethod without failed speculation list");
4115     jvmci_nmethod_data()->add_failed_speculation(this, speculation);
4116     thread->set_pending_failed_speculation(0);
4117   }
4118 }
4119 
4120 const char* nmethod::jvmci_name() {
4121   if (jvmci_nmethod_data() != nullptr) {
4122     return jvmci_nmethod_data()->name();
4123   }
4124   return nullptr;
4125 }
4126 
4127 bool nmethod::jvmci_skip_profile_deopt() const {
4128   return jvmci_nmethod_data() != nullptr && !jvmci_nmethod_data()->profile_deopt();
4129 }
4130 #endif