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