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