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