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   int nmethod_count;
 123   int total_size;
 124   int relocation_size;
 125   int consts_size;
 126   int insts_size;
 127   int stub_size;
 128   int scopes_data_size;
 129   int scopes_pcs_size;
 130   int dependencies_size;
 131   int handler_table_size;
 132   int nul_chk_table_size;
 133 #if INCLUDE_JVMCI
 134   int speculations_size;
 135   int jvmci_data_size;
 136 #endif
 137   int oops_size;
 138   int 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 %d bytecoded nmethods for %s:", nmethod_count, name);
 162     if (total_size != 0)          tty->print_cr(" total in heap  = %d", 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     = %d", relocation_size);
 165     if (consts_size != 0)         tty->print_cr(" constants      = %d", consts_size);
 166     if (insts_size != 0)          tty->print_cr(" main code      = %d", insts_size);
 167     if (stub_size != 0)           tty->print_cr(" stub code      = %d", stub_size);
 168     if (oops_size != 0)           tty->print_cr(" oops           = %d", oops_size);
 169     if (metadata_size != 0)       tty->print_cr(" metadata       = %d", metadata_size);
 170     if (scopes_data_size != 0)    tty->print_cr(" scopes data    = %d", scopes_data_size);
 171     if (scopes_pcs_size != 0)     tty->print_cr(" scopes pcs     = %d", scopes_pcs_size);
 172     if (dependencies_size != 0)   tty->print_cr(" dependencies   = %d", dependencies_size);
 173     if (handler_table_size != 0)  tty->print_cr(" handler table  = %d", handler_table_size);
 174     if (nul_chk_table_size != 0)  tty->print_cr(" nul chk table  = %d", nul_chk_table_size);
 175 #if INCLUDE_JVMCI
 176     if (speculations_size != 0)   tty->print_cr(" speculations   = %d", speculations_size);
 177     if (jvmci_data_size != 0)     tty->print_cr(" JVMCI data     = %d", jvmci_data_size);
 178 #endif
 179   }
 180 };
 181 
 182 struct native_nmethod_stats_struct {
 183   int native_nmethod_count;
 184   int native_total_size;
 185   int native_relocation_size;
 186   int native_insts_size;
 187   int native_oops_size;
 188   int 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 %d native nmethods:", native_nmethod_count);
 200     if (native_total_size != 0)       tty->print_cr(" N. total size  = %d", native_total_size);
 201     if (native_relocation_size != 0)  tty->print_cr(" N. relocation  = %d", native_relocation_size);
 202     if (native_insts_size != 0)       tty->print_cr(" N. main code   = %d", native_insts_size);
 203     if (native_oops_size != 0)        tty->print_cr(" N. oops        = %d", native_oops_size);
 204     if (native_metadata_size != 0)    tty->print_cr(" N. metadata    = %d", native_metadata_size);
 205   }
 206 };
 207 
 208 struct pc_nmethod_stats_struct {
 209   int pc_desc_resets;   // number of resets (= number of caches)
 210   int pc_desc_queries;  // queries to nmethod::find_pc_desc
 211   int pc_desc_approx;   // number of those which have approximate true
 212   int pc_desc_repeats;  // number of _pc_descs[0] hits
 213   int pc_desc_hits;     // number of LRU cache hits
 214   int pc_desc_tests;    // total number of PcDesc examinations
 215   int pc_desc_searches; // total number of quasi-binary search steps
 216   int pc_desc_adds;     // number of LUR cache insertions
 217 
 218   void print_pc_stats() {
 219     tty->print_cr("PcDesc Statistics:  %d 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=%d/%d, hits=%d+%d, tests=%d+%d, adds=%d",
 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((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(int 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     MutexLocker ml(CompiledMethod_lock->owned_by_self() ? nullptr : CompiledMethod_lock, 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 &= ~_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 &= ~_unloading_cycle_mask;
1685     state |= 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 = RawAccess<MO_RELAXED>::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   RawAccess<MO_RELAXED>::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 
2153 void nmethod::check_all_dependencies(DepChange& changes) {
2154   // Checked dependencies are allocated into this ResourceMark
2155   ResourceMark rm;
2156 
2157   // Turn off dependency tracing while actually testing dependencies.
2158   NOT_PRODUCT( FlagSetting fs(Dependencies::_verify_in_progress, true));
2159 
2160   typedef ResourceHashtable<DependencySignature, int, 11027,
2161                             AnyObj::RESOURCE_AREA, mtInternal,
2162                             &DependencySignature::hash,
2163                             &DependencySignature::equals> DepTable;
2164 
2165   DepTable* table = new DepTable();
2166 
2167   // Iterate over live nmethods and check dependencies of all nmethods that are not
2168   // marked for deoptimization. A particular dependency is only checked once.
2169   NMethodIterator iter(NMethodIterator::only_not_unloading);
2170   while(iter.next()) {
2171     nmethod* nm = iter.method();
2172     // Only notify for live nmethods
2173     if (!nm->is_marked_for_deoptimization()) {
2174       for (Dependencies::DepStream deps(nm); deps.next(); ) {
2175         // Construct abstraction of a dependency.
2176         DependencySignature* current_sig = new DependencySignature(deps);
2177 
2178         // Determine if dependency is already checked. table->put(...) returns
2179         // 'true' if the dependency is added (i.e., was not in the hashtable).
2180         if (table->put(*current_sig, 1)) {
2181           if (deps.check_dependency() != nullptr) {
2182             // Dependency checking failed. Print out information about the failed
2183             // dependency and finally fail with an assert. We can fail here, since
2184             // dependency checking is never done in a product build.
2185             tty->print_cr("Failed dependency:");
2186             changes.print();
2187             nm->print();
2188             nm->print_dependencies_on(tty);
2189             assert(false, "Should have been marked for deoptimization");
2190           }
2191         }
2192       }
2193     }
2194   }
2195 }
2196 
2197 bool nmethod::check_dependency_on(DepChange& changes) {
2198   // What has happened:
2199   // 1) a new class dependee has been added
2200   // 2) dependee and all its super classes have been marked
2201   bool found_check = false;  // set true if we are upset
2202   for (Dependencies::DepStream deps(this); deps.next(); ) {
2203     // Evaluate only relevant dependencies.
2204     if (deps.spot_check_dependency_at(changes) != nullptr) {
2205       found_check = true;
2206       NOT_DEBUG(break);
2207     }
2208   }
2209   return found_check;
2210 }
2211 
2212 // Called from mark_for_deoptimization, when dependee is invalidated.
2213 bool nmethod::is_dependent_on_method(Method* dependee) {
2214   for (Dependencies::DepStream deps(this); deps.next(); ) {
2215     if (deps.type() != Dependencies::evol_method)
2216       continue;
2217     Method* method = deps.method_argument(0);
2218     if (method == dependee) return true;
2219   }
2220   return false;
2221 }
2222 
2223 void nmethod_init() {
2224   // make sure you didn't forget to adjust the filler fields
2225   assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word");
2226 }
2227 
2228 // -----------------------------------------------------------------------------
2229 // Verification
2230 
2231 class VerifyOopsClosure: public OopClosure {
2232   nmethod* _nm;
2233   bool     _ok;
2234 public:
2235   VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { }
2236   bool ok() { return _ok; }
2237   virtual void do_oop(oop* p) {
2238     if (oopDesc::is_oop_or_null(*p)) return;
2239     // Print diagnostic information before calling print_nmethod().
2240     // Assertions therein might prevent call from returning.
2241     tty->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)",
2242                   p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm));
2243     if (_ok) {
2244       _nm->print_nmethod(true);
2245       _ok = false;
2246     }
2247   }
2248   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
2249 };
2250 
2251 class VerifyMetadataClosure: public MetadataClosure {
2252  public:
2253   void do_metadata(Metadata* md) {
2254     if (md->is_method()) {
2255       Method* method = (Method*)md;
2256       assert(!method->is_old(), "Should not be installing old methods");
2257     }
2258   }
2259 };
2260 
2261 
2262 void nmethod::verify() {
2263   if (is_not_entrant())
2264     return;
2265 
2266   // Make sure all the entry points are correctly aligned for patching.
2267   NativeJump::check_verified_entry_alignment(entry_point(), verified_entry_point());
2268 
2269   // assert(oopDesc::is_oop(method()), "must be valid");
2270 
2271   ResourceMark rm;
2272 
2273   if (!CodeCache::contains(this)) {
2274     fatal("nmethod at " INTPTR_FORMAT " not in zone", p2i(this));
2275   }
2276 
2277   if(is_native_method() )
2278     return;
2279 
2280   nmethod* nm = CodeCache::find_nmethod(verified_entry_point());
2281   if (nm != this) {
2282     fatal("findNMethod did not find this nmethod (" INTPTR_FORMAT ")", p2i(this));
2283   }
2284 
2285   for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
2286     if (! p->verify(this)) {
2287       tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", p2i(this));
2288     }
2289   }
2290 
2291 #ifdef ASSERT
2292 #if INCLUDE_JVMCI
2293   {
2294     // Verify that implicit exceptions that deoptimize have a PcDesc and OopMap
2295     ImmutableOopMapSet* oms = oop_maps();
2296     ImplicitExceptionTable implicit_table(this);
2297     for (uint i = 0; i < implicit_table.len(); i++) {
2298       int exec_offset = (int) implicit_table.get_exec_offset(i);
2299       if (implicit_table.get_exec_offset(i) == implicit_table.get_cont_offset(i)) {
2300         assert(pc_desc_at(code_begin() + exec_offset) != nullptr, "missing PcDesc");
2301         bool found = false;
2302         for (int i = 0, imax = oms->count(); i < imax; i++) {
2303           if (oms->pair_at(i)->pc_offset() == exec_offset) {
2304             found = true;
2305             break;
2306           }
2307         }
2308         assert(found, "missing oopmap");
2309       }
2310     }
2311   }
2312 #endif
2313 #endif
2314 
2315   VerifyOopsClosure voc(this);
2316   oops_do(&voc);
2317   assert(voc.ok(), "embedded oops must be OK");
2318   Universe::heap()->verify_nmethod(this);
2319 
2320   assert(_oops_do_mark_link == nullptr, "_oops_do_mark_link for %s should be nullptr but is " PTR_FORMAT,
2321          nm->method()->external_name(), p2i(_oops_do_mark_link));
2322   verify_scopes();
2323 
2324   CompiledICLocker nm_verify(this);
2325   VerifyMetadataClosure vmc;
2326   metadata_do(&vmc);
2327 }
2328 
2329 
2330 void nmethod::verify_interrupt_point(address call_site) {
2331 
2332   // Verify IC only when nmethod installation is finished.
2333   if (!is_not_installed()) {
2334     if (CompiledICLocker::is_safe(this)) {
2335       CompiledIC_at(this, call_site);
2336     } else {
2337       CompiledICLocker ml_verify(this);
2338       CompiledIC_at(this, call_site);
2339     }
2340   }
2341 
2342   HandleMark hm(Thread::current());
2343 
2344   PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address());
2345   assert(pd != nullptr, "PcDesc must exist");
2346   for (ScopeDesc* sd = new ScopeDesc(this, pd);
2347        !sd->is_top(); sd = sd->sender()) {
2348     sd->verify();
2349   }
2350 }
2351 
2352 void nmethod::verify_scopes() {
2353   if( !method() ) return;       // Runtime stubs have no scope
2354   if (method()->is_native()) return; // Ignore stub methods.
2355   // iterate through all interrupt point
2356   // and verify the debug information is valid.
2357   RelocIterator iter((nmethod*)this);
2358   while (iter.next()) {
2359     address stub = nullptr;
2360     switch (iter.type()) {
2361       case relocInfo::virtual_call_type:
2362         verify_interrupt_point(iter.addr());
2363         break;
2364       case relocInfo::opt_virtual_call_type:
2365         stub = iter.opt_virtual_call_reloc()->static_stub();
2366         verify_interrupt_point(iter.addr());
2367         break;
2368       case relocInfo::static_call_type:
2369         stub = iter.static_call_reloc()->static_stub();
2370         //verify_interrupt_point(iter.addr());
2371         break;
2372       case relocInfo::runtime_call_type:
2373       case relocInfo::runtime_call_w_cp_type: {
2374         address destination = iter.reloc()->value();
2375         // Right now there is no way to find out which entries support
2376         // an interrupt point.  It would be nice if we had this
2377         // information in a table.
2378         break;
2379       }
2380       default:
2381         break;
2382     }
2383     assert(stub == nullptr || stub_contains(stub), "static call stub outside stub section");
2384   }
2385 }
2386 
2387 
2388 // -----------------------------------------------------------------------------
2389 // Printing operations
2390 
2391 void nmethod::print() const {
2392   ttyLocker ttyl;   // keep the following output all in one block
2393   print(tty);
2394 }
2395 
2396 void nmethod::print(outputStream* st) const {
2397   ResourceMark rm;
2398 
2399   st->print("Compiled method ");
2400 
2401   if (is_compiled_by_c1()) {
2402     st->print("(c1) ");
2403   } else if (is_compiled_by_c2()) {
2404     st->print("(c2) ");
2405   } else if (is_compiled_by_jvmci()) {
2406     st->print("(JVMCI) ");
2407   } else {
2408     st->print("(n/a) ");
2409   }
2410 
2411   print_on(st, nullptr);
2412 
2413   if (WizardMode) {
2414     st->print("((nmethod*) " INTPTR_FORMAT ") ", p2i(this));
2415     st->print(" for method " INTPTR_FORMAT , p2i(method()));
2416     st->print(" { ");
2417     st->print_cr("%s ", state());
2418     st->print_cr("}:");
2419   }
2420   if (size              () > 0) st->print_cr(" total in heap  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2421                                              p2i(this),
2422                                              p2i(this) + size(),
2423                                              size());
2424   if (relocation_size   () > 0) st->print_cr(" relocation     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2425                                              p2i(relocation_begin()),
2426                                              p2i(relocation_end()),
2427                                              relocation_size());
2428   if (consts_size       () > 0) st->print_cr(" constants      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2429                                              p2i(consts_begin()),
2430                                              p2i(consts_end()),
2431                                              consts_size());
2432   if (insts_size        () > 0) st->print_cr(" main code      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2433                                              p2i(insts_begin()),
2434                                              p2i(insts_end()),
2435                                              insts_size());
2436   if (stub_size         () > 0) st->print_cr(" stub code      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2437                                              p2i(stub_begin()),
2438                                              p2i(stub_end()),
2439                                              stub_size());
2440   if (oops_size         () > 0) st->print_cr(" oops           [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2441                                              p2i(oops_begin()),
2442                                              p2i(oops_end()),
2443                                              oops_size());
2444   if (metadata_size     () > 0) st->print_cr(" metadata       [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2445                                              p2i(metadata_begin()),
2446                                              p2i(metadata_end()),
2447                                              metadata_size());
2448   if (scopes_data_size  () > 0) st->print_cr(" scopes data    [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2449                                              p2i(scopes_data_begin()),
2450                                              p2i(scopes_data_end()),
2451                                              scopes_data_size());
2452   if (scopes_pcs_size   () > 0) st->print_cr(" scopes pcs     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2453                                              p2i(scopes_pcs_begin()),
2454                                              p2i(scopes_pcs_end()),
2455                                              scopes_pcs_size());
2456   if (dependencies_size () > 0) st->print_cr(" dependencies   [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2457                                              p2i(dependencies_begin()),
2458                                              p2i(dependencies_end()),
2459                                              dependencies_size());
2460   if (handler_table_size() > 0) st->print_cr(" handler table  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2461                                              p2i(handler_table_begin()),
2462                                              p2i(handler_table_end()),
2463                                              handler_table_size());
2464   if (nul_chk_table_size() > 0) st->print_cr(" nul chk table  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2465                                              p2i(nul_chk_table_begin()),
2466                                              p2i(nul_chk_table_end()),
2467                                              nul_chk_table_size());
2468 #if INCLUDE_JVMCI
2469   if (speculations_size () > 0) st->print_cr(" speculations   [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2470                                              p2i(speculations_begin()),
2471                                              p2i(speculations_end()),
2472                                              speculations_size());
2473   if (jvmci_data_size   () > 0) st->print_cr(" JVMCI data     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2474                                              p2i(jvmci_data_begin()),
2475                                              p2i(jvmci_data_end()),
2476                                              jvmci_data_size());
2477 #endif
2478 }
2479 
2480 void nmethod::print_code() {
2481   ResourceMark m;
2482   ttyLocker ttyl;
2483   // Call the specialized decode method of this class.
2484   decode(tty);
2485 }
2486 
2487 #ifndef PRODUCT  // called InstanceKlass methods are available only then. Declared as PRODUCT_RETURN
2488 
2489 void nmethod::print_dependencies_on(outputStream* out) {
2490   ResourceMark rm;
2491   stringStream st;
2492   st.print_cr("Dependencies:");
2493   for (Dependencies::DepStream deps(this); deps.next(); ) {
2494     deps.print_dependency(&st);
2495     InstanceKlass* ctxk = deps.context_type();
2496     if (ctxk != nullptr) {
2497       if (ctxk->is_dependent_nmethod(this)) {
2498         st.print_cr("   [nmethod<=klass]%s", ctxk->external_name());
2499       }
2500     }
2501     deps.log_dependency();  // put it into the xml log also
2502   }
2503   out->print_raw(st.as_string());
2504 }
2505 #endif
2506 
2507 #if defined(SUPPORT_DATA_STRUCTS)
2508 
2509 // Print the oops from the underlying CodeBlob.
2510 void nmethod::print_oops(outputStream* st) {
2511   ResourceMark m;
2512   st->print("Oops:");
2513   if (oops_begin() < oops_end()) {
2514     st->cr();
2515     for (oop* p = oops_begin(); p < oops_end(); p++) {
2516       Disassembler::print_location((unsigned char*)p, (unsigned char*)oops_begin(), (unsigned char*)oops_end(), st, true, false);
2517       st->print(PTR_FORMAT " ", *((uintptr_t*)p));
2518       if (Universe::contains_non_oop_word(p)) {
2519         st->print_cr("NON_OOP");
2520         continue;  // skip non-oops
2521       }
2522       if (*p == nullptr) {
2523         st->print_cr("nullptr-oop");
2524         continue;  // skip non-oops
2525       }
2526       (*p)->print_value_on(st);
2527       st->cr();
2528     }
2529   } else {
2530     st->print_cr(" <list empty>");
2531   }
2532 }
2533 
2534 // Print metadata pool.
2535 void nmethod::print_metadata(outputStream* st) {
2536   ResourceMark m;
2537   st->print("Metadata:");
2538   if (metadata_begin() < metadata_end()) {
2539     st->cr();
2540     for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
2541       Disassembler::print_location((unsigned char*)p, (unsigned char*)metadata_begin(), (unsigned char*)metadata_end(), st, true, false);
2542       st->print(PTR_FORMAT " ", *((uintptr_t*)p));
2543       if (*p && *p != Universe::non_oop_word()) {
2544         (*p)->print_value_on(st);
2545       }
2546       st->cr();
2547     }
2548   } else {
2549     st->print_cr(" <list empty>");
2550   }
2551 }
2552 
2553 #ifndef PRODUCT  // ScopeDesc::print_on() is available only then. Declared as PRODUCT_RETURN
2554 void nmethod::print_scopes_on(outputStream* st) {
2555   // Find the first pc desc for all scopes in the code and print it.
2556   ResourceMark rm;
2557   st->print("scopes:");
2558   if (scopes_pcs_begin() < scopes_pcs_end()) {
2559     st->cr();
2560     for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
2561       if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null)
2562         continue;
2563 
2564       ScopeDesc* sd = scope_desc_at(p->real_pc(this));
2565       while (sd != nullptr) {
2566         sd->print_on(st, p);  // print output ends with a newline
2567         sd = sd->sender();
2568       }
2569     }
2570   } else {
2571     st->print_cr(" <list empty>");
2572   }
2573 }
2574 #endif
2575 
2576 #ifndef PRODUCT  // RelocIterator does support printing only then.
2577 void nmethod::print_relocations() {
2578   ResourceMark m;       // in case methods get printed via the debugger
2579   tty->print_cr("relocations:");
2580   RelocIterator iter(this);
2581   iter.print();
2582 }
2583 #endif
2584 
2585 void nmethod::print_pcs_on(outputStream* st) {
2586   ResourceMark m;       // in case methods get printed via debugger
2587   st->print("pc-bytecode offsets:");
2588   if (scopes_pcs_begin() < scopes_pcs_end()) {
2589     st->cr();
2590     for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
2591       p->print_on(st, this);  // print output ends with a newline
2592     }
2593   } else {
2594     st->print_cr(" <list empty>");
2595   }
2596 }
2597 
2598 void nmethod::print_handler_table() {
2599   ExceptionHandlerTable(this).print(code_begin());
2600 }
2601 
2602 void nmethod::print_nul_chk_table() {
2603   ImplicitExceptionTable(this).print(code_begin());
2604 }
2605 
2606 void nmethod::print_recorded_oop(int log_n, int i) {
2607   void* value;
2608 
2609   if (i == 0) {
2610     value = nullptr;
2611   } else {
2612     // Be careful around non-oop words. Don't create an oop
2613     // with that value, or it will assert in verification code.
2614     if (Universe::contains_non_oop_word(oop_addr_at(i))) {
2615       value = Universe::non_oop_word();
2616     } else {
2617       value = oop_at(i);
2618     }
2619   }
2620 
2621   tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(value));
2622 
2623   if (value == Universe::non_oop_word()) {
2624     tty->print("non-oop word");
2625   } else {
2626     if (value == 0) {
2627       tty->print("nullptr-oop");
2628     } else {
2629       oop_at(i)->print_value_on(tty);
2630     }
2631   }
2632 
2633   tty->cr();
2634 }
2635 
2636 void nmethod::print_recorded_oops() {
2637   const int n = oops_count();
2638   const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6;
2639   tty->print("Recorded oops:");
2640   if (n > 0) {
2641     tty->cr();
2642     for (int i = 0; i < n; i++) {
2643       print_recorded_oop(log_n, i);
2644     }
2645   } else {
2646     tty->print_cr(" <list empty>");
2647   }
2648 }
2649 
2650 void nmethod::print_recorded_metadata() {
2651   const int n = metadata_count();
2652   const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6;
2653   tty->print("Recorded metadata:");
2654   if (n > 0) {
2655     tty->cr();
2656     for (int i = 0; i < n; i++) {
2657       Metadata* m = metadata_at(i);
2658       tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(m));
2659       if (m == (Metadata*)Universe::non_oop_word()) {
2660         tty->print("non-metadata word");
2661       } else if (m == nullptr) {
2662         tty->print("nullptr-oop");
2663       } else {
2664         Metadata::print_value_on_maybe_null(tty, m);
2665       }
2666       tty->cr();
2667     }
2668   } else {
2669     tty->print_cr(" <list empty>");
2670   }
2671 }
2672 #endif
2673 
2674 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
2675 
2676 void nmethod::print_constant_pool(outputStream* st) {
2677   //-----------------------------------
2678   //---<  Print the constant pool  >---
2679   //-----------------------------------
2680   int consts_size = this->consts_size();
2681   if ( consts_size > 0 ) {
2682     unsigned char* cstart = this->consts_begin();
2683     unsigned char* cp     = cstart;
2684     unsigned char* cend   = cp + consts_size;
2685     unsigned int   bytes_per_line = 4;
2686     unsigned int   CP_alignment   = 8;
2687     unsigned int   n;
2688 
2689     st->cr();
2690 
2691     //---<  print CP header to make clear what's printed  >---
2692     if( ((uintptr_t)cp&(CP_alignment-1)) == 0 ) {
2693       n = bytes_per_line;
2694       st->print_cr("[Constant Pool]");
2695       Disassembler::print_location(cp, cstart, cend, st, true, true);
2696       Disassembler::print_hexdata(cp, n, st, true);
2697       st->cr();
2698     } else {
2699       n = (uintptr_t)cp&(bytes_per_line-1);
2700       st->print_cr("[Constant Pool (unaligned)]");
2701     }
2702 
2703     //---<  print CP contents, bytes_per_line at a time  >---
2704     while (cp < cend) {
2705       Disassembler::print_location(cp, cstart, cend, st, true, false);
2706       Disassembler::print_hexdata(cp, n, st, false);
2707       cp += n;
2708       n   = bytes_per_line;
2709       st->cr();
2710     }
2711 
2712     //---<  Show potential alignment gap between constant pool and code  >---
2713     cend = code_begin();
2714     if( cp < cend ) {
2715       n = 4;
2716       st->print_cr("[Code entry alignment]");
2717       while (cp < cend) {
2718         Disassembler::print_location(cp, cstart, cend, st, false, false);
2719         cp += n;
2720         st->cr();
2721       }
2722     }
2723   } else {
2724     st->print_cr("[Constant Pool (empty)]");
2725   }
2726   st->cr();
2727 }
2728 
2729 #endif
2730 
2731 // Disassemble this nmethod.
2732 // Print additional debug information, if requested. This could be code
2733 // comments, block comments, profiling counters, etc.
2734 // The undisassembled format is useful no disassembler library is available.
2735 // The resulting hex dump (with markers) can be disassembled later, or on
2736 // another system, when/where a disassembler library is available.
2737 void nmethod::decode2(outputStream* ost) const {
2738 
2739   // Called from frame::back_trace_with_decode without ResourceMark.
2740   ResourceMark rm;
2741 
2742   // Make sure we have a valid stream to print on.
2743   outputStream* st = ost ? ost : tty;
2744 
2745 #if defined(SUPPORT_ABSTRACT_ASSEMBLY) && ! defined(SUPPORT_ASSEMBLY)
2746   const bool use_compressed_format    = true;
2747   const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() ||
2748                                                                   AbstractDisassembler::show_block_comment());
2749 #else
2750   const bool use_compressed_format    = Disassembler::is_abstract();
2751   const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() ||
2752                                                                   AbstractDisassembler::show_block_comment());
2753 #endif
2754 
2755   st->cr();
2756   this->print(st);
2757   st->cr();
2758 
2759 #if defined(SUPPORT_ASSEMBLY)
2760   //----------------------------------
2761   //---<  Print real disassembly  >---
2762   //----------------------------------
2763   if (! use_compressed_format) {
2764     st->print_cr("[Disassembly]");
2765     Disassembler::decode(const_cast<nmethod*>(this), st);
2766     st->bol();
2767     st->print_cr("[/Disassembly]");
2768     return;
2769   }
2770 #endif
2771 
2772 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
2773 
2774   // Compressed undisassembled disassembly format.
2775   // The following status values are defined/supported:
2776   //   = 0 - currently at bol() position, nothing printed yet on current line.
2777   //   = 1 - currently at position after print_location().
2778   //   > 1 - in the midst of printing instruction stream bytes.
2779   int        compressed_format_idx    = 0;
2780   int        code_comment_column      = 0;
2781   const int  instr_maxlen             = Assembler::instr_maxlen();
2782   const uint tabspacing               = 8;
2783   unsigned char* start = this->code_begin();
2784   unsigned char* p     = this->code_begin();
2785   unsigned char* end   = this->code_end();
2786   unsigned char* pss   = p; // start of a code section (used for offsets)
2787 
2788   if ((start == nullptr) || (end == nullptr)) {
2789     st->print_cr("PrintAssembly not possible due to uninitialized section pointers");
2790     return;
2791   }
2792 #endif
2793 
2794 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
2795   //---<  plain abstract disassembly, no comments or anything, just section headers  >---
2796   if (use_compressed_format && ! compressed_with_comments) {
2797     const_cast<nmethod*>(this)->print_constant_pool(st);
2798 
2799     //---<  Open the output (Marker for post-mortem disassembler)  >---
2800     st->print_cr("[MachCode]");
2801     const char* header = nullptr;
2802     address p0 = p;
2803     while (p < end) {
2804       address pp = p;
2805       while ((p < end) && (header == nullptr)) {
2806         header = nmethod_section_label(p);
2807         pp  = p;
2808         p  += Assembler::instr_len(p);
2809       }
2810       if (pp > p0) {
2811         AbstractDisassembler::decode_range_abstract(p0, pp, start, end, st, Assembler::instr_maxlen());
2812         p0 = pp;
2813         p  = pp;
2814         header = nullptr;
2815       } else if (header != nullptr) {
2816         st->bol();
2817         st->print_cr("%s", header);
2818         header = nullptr;
2819       }
2820     }
2821     //---<  Close the output (Marker for post-mortem disassembler)  >---
2822     st->bol();
2823     st->print_cr("[/MachCode]");
2824     return;
2825   }
2826 #endif
2827 
2828 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
2829   //---<  abstract disassembly with comments and section headers merged in  >---
2830   if (compressed_with_comments) {
2831     const_cast<nmethod*>(this)->print_constant_pool(st);
2832 
2833     //---<  Open the output (Marker for post-mortem disassembler)  >---
2834     st->print_cr("[MachCode]");
2835     while ((p < end) && (p != nullptr)) {
2836       const int instruction_size_in_bytes = Assembler::instr_len(p);
2837 
2838       //---<  Block comments for nmethod. Interrupts instruction stream, if any.  >---
2839       // Outputs a bol() before and a cr() after, but only if a comment is printed.
2840       // Prints nmethod_section_label as well.
2841       if (AbstractDisassembler::show_block_comment()) {
2842         print_block_comment(st, p);
2843         if (st->position() == 0) {
2844           compressed_format_idx = 0;
2845         }
2846       }
2847 
2848       //---<  New location information after line break  >---
2849       if (compressed_format_idx == 0) {
2850         code_comment_column   = Disassembler::print_location(p, pss, end, st, false, false);
2851         compressed_format_idx = 1;
2852       }
2853 
2854       //---<  Code comment for current instruction. Address range [p..(p+len))  >---
2855       unsigned char* p_end = p + (ssize_t)instruction_size_in_bytes;
2856       S390_ONLY(if (p_end > end) p_end = end;) // avoid getting past the end
2857 
2858       if (AbstractDisassembler::show_comment() && const_cast<nmethod*>(this)->has_code_comment(p, p_end)) {
2859         //---<  interrupt instruction byte stream for code comment  >---
2860         if (compressed_format_idx > 1) {
2861           st->cr();  // interrupt byte stream
2862           st->cr();  // add an empty line
2863           code_comment_column = Disassembler::print_location(p, pss, end, st, false, false);
2864         }
2865         const_cast<nmethod*>(this)->print_code_comment_on(st, code_comment_column, p, p_end );
2866         st->bol();
2867         compressed_format_idx = 0;
2868       }
2869 
2870       //---<  New location information after line break  >---
2871       if (compressed_format_idx == 0) {
2872         code_comment_column   = Disassembler::print_location(p, pss, end, st, false, false);
2873         compressed_format_idx = 1;
2874       }
2875 
2876       //---<  Nicely align instructions for readability  >---
2877       if (compressed_format_idx > 1) {
2878         Disassembler::print_delimiter(st);
2879       }
2880 
2881       //---<  Now, finally, print the actual instruction bytes  >---
2882       unsigned char* p0 = p;
2883       p = Disassembler::decode_instruction_abstract(p, st, instruction_size_in_bytes, instr_maxlen);
2884       compressed_format_idx += p - p0;
2885 
2886       if (Disassembler::start_newline(compressed_format_idx-1)) {
2887         st->cr();
2888         compressed_format_idx = 0;
2889       }
2890     }
2891     //---<  Close the output (Marker for post-mortem disassembler)  >---
2892     st->bol();
2893     st->print_cr("[/MachCode]");
2894     return;
2895   }
2896 #endif
2897 }
2898 
2899 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
2900 
2901 const char* nmethod::reloc_string_for(u_char* begin, u_char* end) {
2902   RelocIterator iter(this, begin, end);
2903   bool have_one = false;
2904   while (iter.next()) {
2905     have_one = true;
2906     switch (iter.type()) {
2907         case relocInfo::none:                  return "no_reloc";
2908         case relocInfo::oop_type: {
2909           // Get a non-resizable resource-allocated stringStream.
2910           // Our callees make use of (nested) ResourceMarks.
2911           stringStream st(NEW_RESOURCE_ARRAY(char, 1024), 1024);
2912           oop_Relocation* r = iter.oop_reloc();
2913           oop obj = r->oop_value();
2914           st.print("oop(");
2915           if (obj == nullptr) st.print("nullptr");
2916           else obj->print_value_on(&st);
2917           st.print(")");
2918           return st.as_string();
2919         }
2920         case relocInfo::metadata_type: {
2921           stringStream st;
2922           metadata_Relocation* r = iter.metadata_reloc();
2923           Metadata* obj = r->metadata_value();
2924           st.print("metadata(");
2925           if (obj == nullptr) st.print("nullptr");
2926           else obj->print_value_on(&st);
2927           st.print(")");
2928           return st.as_string();
2929         }
2930         case relocInfo::runtime_call_type:
2931         case relocInfo::runtime_call_w_cp_type: {
2932           stringStream st;
2933           st.print("runtime_call");
2934           CallRelocation* r = (CallRelocation*)iter.reloc();
2935           address dest = r->destination();
2936           CodeBlob* cb = CodeCache::find_blob(dest);
2937           if (cb != nullptr) {
2938             st.print(" %s", cb->name());
2939           } else {
2940             ResourceMark rm;
2941             const int buflen = 1024;
2942             char* buf = NEW_RESOURCE_ARRAY(char, buflen);
2943             int offset;
2944             if (os::dll_address_to_function_name(dest, buf, buflen, &offset)) {
2945               st.print(" %s", buf);
2946               if (offset != 0) {
2947                 st.print("+%d", offset);
2948               }
2949             }
2950           }
2951           return st.as_string();
2952         }
2953         case relocInfo::virtual_call_type: {
2954           stringStream st;
2955           st.print_raw("virtual_call");
2956           virtual_call_Relocation* r = iter.virtual_call_reloc();
2957           Method* m = r->method_value();
2958           if (m != nullptr) {
2959             assert(m->is_method(), "");
2960             m->print_short_name(&st);
2961           }
2962           return st.as_string();
2963         }
2964         case relocInfo::opt_virtual_call_type: {
2965           stringStream st;
2966           st.print_raw("optimized virtual_call");
2967           opt_virtual_call_Relocation* r = iter.opt_virtual_call_reloc();
2968           Method* m = r->method_value();
2969           if (m != nullptr) {
2970             assert(m->is_method(), "");
2971             m->print_short_name(&st);
2972           }
2973           return st.as_string();
2974         }
2975         case relocInfo::static_call_type: {
2976           stringStream st;
2977           st.print_raw("static_call");
2978           static_call_Relocation* r = iter.static_call_reloc();
2979           Method* m = r->method_value();
2980           if (m != nullptr) {
2981             assert(m->is_method(), "");
2982             m->print_short_name(&st);
2983           }
2984           return st.as_string();
2985         }
2986         case relocInfo::static_stub_type:      return "static_stub";
2987         case relocInfo::external_word_type:    return "external_word";
2988         case relocInfo::internal_word_type:    return "internal_word";
2989         case relocInfo::section_word_type:     return "section_word";
2990         case relocInfo::poll_type:             return "poll";
2991         case relocInfo::poll_return_type:      return "poll_return";
2992         case relocInfo::trampoline_stub_type:  return "trampoline_stub";
2993         case relocInfo::type_mask:             return "type_bit_mask";
2994 
2995         default:
2996           break;
2997     }
2998   }
2999   return have_one ? "other" : nullptr;
3000 }
3001 
3002 // Return the last scope in (begin..end]
3003 ScopeDesc* nmethod::scope_desc_in(address begin, address end) {
3004   PcDesc* p = pc_desc_near(begin+1);
3005   if (p != nullptr && p->real_pc(this) <= end) {
3006     return new ScopeDesc(this, p);
3007   }
3008   return nullptr;
3009 }
3010 
3011 const char* nmethod::nmethod_section_label(address pos) const {
3012   const char* label = nullptr;
3013   if (pos == code_begin())                                              label = "[Instructions begin]";
3014   if (pos == entry_point())                                             label = "[Entry Point]";
3015   if (pos == verified_entry_point())                                    label = "[Verified Entry Point]";
3016   if (has_method_handle_invokes() && (pos == deopt_mh_handler_begin())) label = "[Deopt MH Handler Code]";
3017   if (pos == consts_begin() && pos != insts_begin())                    label = "[Constants]";
3018   // Check stub_code before checking exception_handler or deopt_handler.
3019   if (pos == this->stub_begin())                                        label = "[Stub Code]";
3020   if (JVMCI_ONLY(_exception_offset >= 0 &&) pos == exception_begin())           label = "[Exception Handler]";
3021   if (JVMCI_ONLY(_deopt_handler_begin != nullptr &&) pos == deopt_handler_begin()) label = "[Deopt Handler Code]";
3022   return label;
3023 }
3024 
3025 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin, bool print_section_labels) const {
3026   if (print_section_labels) {
3027     const char* label = nmethod_section_label(block_begin);
3028     if (label != nullptr) {
3029       stream->bol();
3030       stream->print_cr("%s", label);
3031     }
3032   }
3033 
3034   if (block_begin == entry_point()) {
3035     Method* m = method();
3036     if (m != nullptr) {
3037       stream->print("  # ");
3038       m->print_value_on(stream);
3039       stream->cr();
3040     }
3041     if (m != nullptr && !is_osr_method()) {
3042       ResourceMark rm;
3043       int sizeargs = m->size_of_parameters();
3044       BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs);
3045       VMRegPair* regs   = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs);
3046       {
3047         int sig_index = 0;
3048         if (!m->is_static())
3049           sig_bt[sig_index++] = T_OBJECT; // 'this'
3050         for (SignatureStream ss(m->signature()); !ss.at_return_type(); ss.next()) {
3051           BasicType t = ss.type();
3052           sig_bt[sig_index++] = t;
3053           if (type2size[t] == 2) {
3054             sig_bt[sig_index++] = T_VOID;
3055           } else {
3056             assert(type2size[t] == 1, "size is 1 or 2");
3057           }
3058         }
3059         assert(sig_index == sizeargs, "");
3060       }
3061       const char* spname = "sp"; // make arch-specific?
3062       intptr_t out_preserve = SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs);
3063       int stack_slot_offset = this->frame_size() * wordSize;
3064       int tab1 = 14, tab2 = 24;
3065       int sig_index = 0;
3066       int arg_index = (m->is_static() ? 0 : -1);
3067       bool did_old_sp = false;
3068       for (SignatureStream ss(m->signature()); !ss.at_return_type(); ) {
3069         bool at_this = (arg_index == -1);
3070         bool at_old_sp = false;
3071         BasicType t = (at_this ? T_OBJECT : ss.type());
3072         assert(t == sig_bt[sig_index], "sigs in sync");
3073         if (at_this)
3074           stream->print("  # this: ");
3075         else
3076           stream->print("  # parm%d: ", arg_index);
3077         stream->move_to(tab1);
3078         VMReg fst = regs[sig_index].first();
3079         VMReg snd = regs[sig_index].second();
3080         if (fst->is_reg()) {
3081           stream->print("%s", fst->name());
3082           if (snd->is_valid())  {
3083             stream->print(":%s", snd->name());
3084           }
3085         } else if (fst->is_stack()) {
3086           int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset;
3087           if (offset == stack_slot_offset)  at_old_sp = true;
3088           stream->print("[%s+0x%x]", spname, offset);
3089         } else {
3090           stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd);
3091         }
3092         stream->print(" ");
3093         stream->move_to(tab2);
3094         stream->print("= ");
3095         if (at_this) {
3096           m->method_holder()->print_value_on(stream);
3097         } else {
3098           bool did_name = false;
3099           if (!at_this && ss.is_reference()) {
3100             Symbol* name = ss.as_symbol();
3101             name->print_value_on(stream);
3102             did_name = true;
3103           }
3104           if (!did_name)
3105             stream->print("%s", type2name(t));
3106         }
3107         if (at_old_sp) {
3108           stream->print("  (%s of caller)", spname);
3109           did_old_sp = true;
3110         }
3111         stream->cr();
3112         sig_index += type2size[t];
3113         arg_index += 1;
3114         if (!at_this)  ss.next();
3115       }
3116       if (!did_old_sp) {
3117         stream->print("  # ");
3118         stream->move_to(tab1);
3119         stream->print("[%s+0x%x]", spname, stack_slot_offset);
3120         stream->print("  (%s of caller)", spname);
3121         stream->cr();
3122       }
3123     }
3124   }
3125 }
3126 
3127 // Returns whether this nmethod has code comments.
3128 bool nmethod::has_code_comment(address begin, address end) {
3129   // scopes?
3130   ScopeDesc* sd  = scope_desc_in(begin, end);
3131   if (sd != nullptr) return true;
3132 
3133   // relocations?
3134   const char* str = reloc_string_for(begin, end);
3135   if (str != nullptr) return true;
3136 
3137   // implicit exceptions?
3138   int cont_offset = ImplicitExceptionTable(this).continuation_offset(begin - code_begin());
3139   if (cont_offset != 0) return true;
3140 
3141   return false;
3142 }
3143 
3144 void nmethod::print_code_comment_on(outputStream* st, int column, address begin, address end) {
3145   ImplicitExceptionTable implicit_table(this);
3146   int pc_offset = begin - code_begin();
3147   int cont_offset = implicit_table.continuation_offset(pc_offset);
3148   bool oop_map_required = false;
3149   if (cont_offset != 0) {
3150     st->move_to(column, 6, 0);
3151     if (pc_offset == cont_offset) {
3152       st->print("; implicit exception: deoptimizes");
3153       oop_map_required = true;
3154     } else {
3155       st->print("; implicit exception: dispatches to " INTPTR_FORMAT, p2i(code_begin() + cont_offset));
3156     }
3157   }
3158 
3159   // Find an oopmap in (begin, end].  We use the odd half-closed
3160   // interval so that oop maps and scope descs which are tied to the
3161   // byte after a call are printed with the call itself.  OopMaps
3162   // associated with implicit exceptions are printed with the implicit
3163   // instruction.
3164   address base = code_begin();
3165   ImmutableOopMapSet* oms = oop_maps();
3166   if (oms != nullptr) {
3167     for (int i = 0, imax = oms->count(); i < imax; i++) {
3168       const ImmutableOopMapPair* pair = oms->pair_at(i);
3169       const ImmutableOopMap* om = pair->get_from(oms);
3170       address pc = base + pair->pc_offset();
3171       if (pc >= begin) {
3172 #if INCLUDE_JVMCI
3173         bool is_implicit_deopt = implicit_table.continuation_offset(pair->pc_offset()) == (uint) pair->pc_offset();
3174 #else
3175         bool is_implicit_deopt = false;
3176 #endif
3177         if (is_implicit_deopt ? pc == begin : pc > begin && pc <= end) {
3178           st->move_to(column, 6, 0);
3179           st->print("; ");
3180           om->print_on(st);
3181           oop_map_required = false;
3182         }
3183       }
3184       if (pc > end) {
3185         break;
3186       }
3187     }
3188   }
3189   assert(!oop_map_required, "missed oopmap");
3190 
3191   Thread* thread = Thread::current();
3192 
3193   // Print any debug info present at this pc.
3194   ScopeDesc* sd  = scope_desc_in(begin, end);
3195   if (sd != nullptr) {
3196     st->move_to(column, 6, 0);
3197     if (sd->bci() == SynchronizationEntryBCI) {
3198       st->print(";*synchronization entry");
3199     } else if (sd->bci() == AfterBci) {
3200       st->print(";* method exit (unlocked if synchronized)");
3201     } else if (sd->bci() == UnwindBci) {
3202       st->print(";* unwind (locked if synchronized)");
3203     } else if (sd->bci() == AfterExceptionBci) {
3204       st->print(";* unwind (unlocked if synchronized)");
3205     } else if (sd->bci() == UnknownBci) {
3206       st->print(";* unknown");
3207     } else if (sd->bci() == InvalidFrameStateBci) {
3208       st->print(";* invalid frame state");
3209     } else {
3210       if (sd->method() == nullptr) {
3211         st->print("method is nullptr");
3212       } else if (sd->method()->is_native()) {
3213         st->print("method is native");
3214       } else {
3215         Bytecodes::Code bc = sd->method()->java_code_at(sd->bci());
3216         st->print(";*%s", Bytecodes::name(bc));
3217         switch (bc) {
3218         case Bytecodes::_invokevirtual:
3219         case Bytecodes::_invokespecial:
3220         case Bytecodes::_invokestatic:
3221         case Bytecodes::_invokeinterface:
3222           {
3223             Bytecode_invoke invoke(methodHandle(thread, sd->method()), sd->bci());
3224             st->print(" ");
3225             if (invoke.name() != nullptr)
3226               invoke.name()->print_symbol_on(st);
3227             else
3228               st->print("<UNKNOWN>");
3229             break;
3230           }
3231         case Bytecodes::_getfield:
3232         case Bytecodes::_putfield:
3233         case Bytecodes::_getstatic:
3234         case Bytecodes::_putstatic:
3235           {
3236             Bytecode_field field(methodHandle(thread, sd->method()), sd->bci());
3237             st->print(" ");
3238             if (field.name() != nullptr)
3239               field.name()->print_symbol_on(st);
3240             else
3241               st->print("<UNKNOWN>");
3242           }
3243         default:
3244           break;
3245         }
3246       }
3247       st->print(" {reexecute=%d rethrow=%d return_oop=%d}", sd->should_reexecute(), sd->rethrow_exception(), sd->return_oop());
3248     }
3249 
3250     // Print all scopes
3251     for (;sd != nullptr; sd = sd->sender()) {
3252       st->move_to(column, 6, 0);
3253       st->print("; -");
3254       if (sd->should_reexecute()) {
3255         st->print(" (reexecute)");
3256       }
3257       if (sd->method() == nullptr) {
3258         st->print("method is nullptr");
3259       } else {
3260         sd->method()->print_short_name(st);
3261       }
3262       int lineno = sd->method()->line_number_from_bci(sd->bci());
3263       if (lineno != -1) {
3264         st->print("@%d (line %d)", sd->bci(), lineno);
3265       } else {
3266         st->print("@%d", sd->bci());
3267       }
3268       st->cr();
3269     }
3270   }
3271 
3272   // Print relocation information
3273   // Prevent memory leak: allocating without ResourceMark.
3274   ResourceMark rm;
3275   const char* str = reloc_string_for(begin, end);
3276   if (str != nullptr) {
3277     if (sd != nullptr) st->cr();
3278     st->move_to(column, 6, 0);
3279     st->print(";   {%s}", str);
3280   }
3281 }
3282 
3283 #endif
3284 
3285 class DirectNativeCallWrapper: public NativeCallWrapper {
3286 private:
3287   NativeCall* _call;
3288 
3289 public:
3290   DirectNativeCallWrapper(NativeCall* call) : _call(call) {}
3291 
3292   virtual address destination() const { return _call->destination(); }
3293   virtual address instruction_address() const { return _call->instruction_address(); }
3294   virtual address next_instruction_address() const { return _call->next_instruction_address(); }
3295   virtual address return_address() const { return _call->return_address(); }
3296 
3297   virtual address get_resolve_call_stub(bool is_optimized) const {
3298     if (is_optimized) {
3299       return SharedRuntime::get_resolve_opt_virtual_call_stub();
3300     }
3301     return SharedRuntime::get_resolve_virtual_call_stub();
3302   }
3303 
3304   virtual void set_destination_mt_safe(address dest) {
3305     _call->set_destination_mt_safe(dest);
3306   }
3307 
3308   virtual void set_to_interpreted(const methodHandle& method, CompiledICInfo& info) {
3309     CompiledDirectStaticCall* csc = CompiledDirectStaticCall::at(instruction_address());
3310     {
3311       csc->set_to_interpreted(method, info.entry());
3312     }
3313   }
3314 
3315   virtual void verify() const {
3316     // make sure code pattern is actually a call imm32 instruction
3317     _call->verify();
3318     _call->verify_alignment();
3319   }
3320 
3321   virtual void verify_resolve_call(address dest) const {
3322     CodeBlob* db = CodeCache::find_blob(dest);
3323     assert(db != nullptr && !db->is_adapter_blob(), "must use stub!");
3324   }
3325 
3326   virtual bool is_call_to_interpreted(address dest) const {
3327     CodeBlob* cb = CodeCache::find_blob(_call->instruction_address());
3328     return cb->contains(dest);
3329   }
3330 
3331   virtual bool is_safe_for_patching() const { return false; }
3332 
3333   virtual NativeInstruction* get_load_instruction(virtual_call_Relocation* r) const {
3334     return nativeMovConstReg_at(r->cached_value());
3335   }
3336 
3337   virtual void *get_data(NativeInstruction* instruction) const {
3338     return (void*)((NativeMovConstReg*) instruction)->data();
3339   }
3340 
3341   virtual void set_data(NativeInstruction* instruction, intptr_t data) {
3342     ((NativeMovConstReg*) instruction)->set_data(data);
3343   }
3344 };
3345 
3346 NativeCallWrapper* nmethod::call_wrapper_at(address call) const {
3347   return new DirectNativeCallWrapper((NativeCall*) call);
3348 }
3349 
3350 NativeCallWrapper* nmethod::call_wrapper_before(address return_pc) const {
3351   return new DirectNativeCallWrapper(nativeCall_before(return_pc));
3352 }
3353 
3354 address nmethod::call_instruction_address(address pc) const {
3355   if (NativeCall::is_call_before(pc)) {
3356     NativeCall *ncall = nativeCall_before(pc);
3357     return ncall->instruction_address();
3358   }
3359   return nullptr;
3360 }
3361 
3362 CompiledStaticCall* nmethod::compiledStaticCall_at(Relocation* call_site) const {
3363   return CompiledDirectStaticCall::at(call_site);
3364 }
3365 
3366 CompiledStaticCall* nmethod::compiledStaticCall_at(address call_site) const {
3367   return CompiledDirectStaticCall::at(call_site);
3368 }
3369 
3370 CompiledStaticCall* nmethod::compiledStaticCall_before(address return_addr) const {
3371   return CompiledDirectStaticCall::before(return_addr);
3372 }
3373 
3374 #if defined(SUPPORT_DATA_STRUCTS)
3375 void nmethod::print_value_on(outputStream* st) const {
3376   st->print("nmethod");
3377   print_on(st, nullptr);
3378 }
3379 #endif
3380 
3381 #ifndef PRODUCT
3382 
3383 void nmethod::print_calls(outputStream* st) {
3384   RelocIterator iter(this);
3385   while (iter.next()) {
3386     switch (iter.type()) {
3387     case relocInfo::virtual_call_type:
3388     case relocInfo::opt_virtual_call_type: {
3389       CompiledICLocker ml_verify(this);
3390       CompiledIC_at(&iter)->print();
3391       break;
3392     }
3393     case relocInfo::static_call_type:
3394       st->print_cr("Static call at " INTPTR_FORMAT, p2i(iter.reloc()->addr()));
3395       CompiledDirectStaticCall::at(iter.reloc())->print();
3396       break;
3397     default:
3398       break;
3399     }
3400   }
3401 }
3402 
3403 void nmethod::print_statistics() {
3404   ttyLocker ttyl;
3405   if (xtty != nullptr)  xtty->head("statistics type='nmethod'");
3406   native_nmethod_stats.print_native_nmethod_stats();
3407 #ifdef COMPILER1
3408   c1_java_nmethod_stats.print_nmethod_stats("C1");
3409 #endif
3410 #ifdef COMPILER2
3411   c2_java_nmethod_stats.print_nmethod_stats("C2");
3412 #endif
3413 #if INCLUDE_JVMCI
3414   jvmci_java_nmethod_stats.print_nmethod_stats("JVMCI");
3415 #endif
3416   unknown_java_nmethod_stats.print_nmethod_stats("Unknown");
3417   DebugInformationRecorder::print_statistics();
3418 #ifndef PRODUCT
3419   pc_nmethod_stats.print_pc_stats();
3420 #endif
3421   Dependencies::print_statistics();
3422   if (xtty != nullptr)  xtty->tail("statistics");
3423 }
3424 
3425 #endif // !PRODUCT
3426 
3427 #if INCLUDE_JVMCI
3428 void nmethod::update_speculation(JavaThread* thread) {
3429   jlong speculation = thread->pending_failed_speculation();
3430   if (speculation != 0) {
3431     guarantee(jvmci_nmethod_data() != nullptr, "failed speculation in nmethod without failed speculation list");
3432     jvmci_nmethod_data()->add_failed_speculation(this, speculation);
3433     thread->set_pending_failed_speculation(0);
3434   }
3435 }
3436 
3437 const char* nmethod::jvmci_name() {
3438   if (jvmci_nmethod_data() != nullptr) {
3439     return jvmci_nmethod_data()->name();
3440   }
3441   return nullptr;
3442 }
3443 #endif