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