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