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