1 /*
   2  * Copyright (c) 1997, 2021, 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 "jvm.h"
  27 #include "asm/assembler.inline.hpp"
  28 #include "code/codeCache.hpp"
  29 #include "code/compiledIC.hpp"
  30 #include "code/compiledMethod.inline.hpp"
  31 #include "code/dependencies.hpp"
  32 #include "code/nativeInst.hpp"
  33 #include "code/nmethod.hpp"
  34 #include "code/scopeDesc.hpp"
  35 #include "compiler/abstractCompiler.hpp"
  36 #include "compiler/compileBroker.hpp"
  37 #include "compiler/compileLog.hpp"
  38 #include "compiler/compilerDirectives.hpp"
  39 #include "compiler/directivesParser.hpp"
  40 #include "compiler/disassembler.hpp"
  41 #include "compiler/oopMap.hpp"
  42 #include "gc/shared/barrierSet.hpp"
  43 #include "gc/shared/barrierSetNMethod.hpp"
  44 #include "gc/shared/collectedHeap.hpp"
  45 #include "interpreter/bytecode.hpp"
  46 #include "logging/log.hpp"
  47 #include "logging/logStream.hpp"
  48 #include "memory/allocation.inline.hpp"
  49 #include "memory/resourceArea.hpp"
  50 #include "memory/universe.hpp"
  51 #include "oops/access.inline.hpp"
  52 #include "oops/klass.inline.hpp"
  53 #include "oops/method.inline.hpp"
  54 #include "oops/methodData.hpp"
  55 #include "oops/oop.inline.hpp"
  56 #include "oops/weakHandle.inline.hpp"
  57 #include "prims/jvmtiImpl.hpp"
  58 #include "prims/jvmtiThreadState.hpp"
  59 #include "prims/methodHandles.hpp"
  60 #include "runtime/atomic.hpp"
  61 #include "runtime/deoptimization.hpp"
  62 #include "runtime/flags/flagSetting.hpp"
  63 #include "runtime/frame.inline.hpp"
  64 #include "runtime/handles.inline.hpp"
  65 #include "runtime/jniHandles.inline.hpp"
  66 #include "runtime/orderAccess.hpp"
  67 #include "runtime/os.hpp"
  68 #include "runtime/safepointVerifiers.hpp"
  69 #include "runtime/serviceThread.hpp"
  70 #include "runtime/sharedRuntime.hpp"
  71 #include "runtime/signature.hpp"
  72 #include "runtime/sweeper.hpp"
  73 #include "runtime/threadWXSetters.inline.hpp"
  74 #include "runtime/vmThread.hpp"
  75 #include "utilities/align.hpp"
  76 #include "utilities/copy.hpp"
  77 #include "utilities/dtrace.hpp"
  78 #include "utilities/events.hpp"
  79 #include "utilities/globalDefinitions.hpp"
  80 #include "utilities/resourceHash.hpp"
  81 #include "utilities/xmlstream.hpp"
  82 #if INCLUDE_JVMCI
  83 #include "jvmci/jvmciRuntime.hpp"
  84 #endif
  85 
  86 #ifdef DTRACE_ENABLED
  87 
  88 // Only bother with this argument setup if dtrace is available
  89 
  90 #define DTRACE_METHOD_UNLOAD_PROBE(method)                                \
  91   {                                                                       \
  92     Method* m = (method);                                                 \
  93     if (m != NULL) {                                                      \
  94       Symbol* klass_name = m->klass_name();                               \
  95       Symbol* name = m->name();                                           \
  96       Symbol* signature = m->signature();                                 \
  97       HOTSPOT_COMPILED_METHOD_UNLOAD(                                     \
  98         (char *) klass_name->bytes(), klass_name->utf8_length(),                   \
  99         (char *) name->bytes(), name->utf8_length(),                               \
 100         (char *) signature->bytes(), signature->utf8_length());                    \
 101     }                                                                     \
 102   }
 103 
 104 #else //  ndef DTRACE_ENABLED
 105 
 106 #define DTRACE_METHOD_UNLOAD_PROBE(method)
 107 
 108 #endif
 109 
 110 //---------------------------------------------------------------------------------
 111 // NMethod statistics
 112 // They are printed under various flags, including:
 113 //   PrintC1Statistics, PrintOptoStatistics, LogVMOutput, and LogCompilation.
 114 // (In the latter two cases, they like other stats are printed to the log only.)
 115 
 116 #ifndef PRODUCT
 117 // These variables are put into one block to reduce relocations
 118 // and make it simpler to print from the debugger.
 119 struct java_nmethod_stats_struct {
 120   int nmethod_count;
 121   int total_size;
 122   int relocation_size;
 123   int consts_size;
 124   int insts_size;
 125   int stub_size;
 126   int scopes_data_size;
 127   int scopes_pcs_size;
 128   int dependencies_size;
 129   int handler_table_size;
 130   int nul_chk_table_size;
 131 #if INCLUDE_JVMCI
 132   int speculations_size;
 133   int jvmci_data_size;
 134 #endif
 135   int oops_size;
 136   int metadata_size;
 137 
 138   void note_nmethod(nmethod* nm) {
 139     nmethod_count += 1;
 140     total_size          += nm->size();
 141     relocation_size     += nm->relocation_size();
 142     consts_size         += nm->consts_size();
 143     insts_size          += nm->insts_size();
 144     stub_size           += nm->stub_size();
 145     oops_size           += nm->oops_size();
 146     metadata_size       += nm->metadata_size();
 147     scopes_data_size    += nm->scopes_data_size();
 148     scopes_pcs_size     += nm->scopes_pcs_size();
 149     dependencies_size   += nm->dependencies_size();
 150     handler_table_size  += nm->handler_table_size();
 151     nul_chk_table_size  += nm->nul_chk_table_size();
 152 #if INCLUDE_JVMCI
 153     speculations_size   += nm->speculations_size();
 154     jvmci_data_size     += nm->jvmci_data_size();
 155 #endif
 156   }
 157   void print_nmethod_stats(const char* name) {
 158     if (nmethod_count == 0)  return;
 159     tty->print_cr("Statistics for %d bytecoded nmethods for %s:", nmethod_count, name);
 160     if (total_size != 0)          tty->print_cr(" total in heap  = %d", total_size);
 161     if (nmethod_count != 0)       tty->print_cr(" header         = " SIZE_FORMAT, nmethod_count * sizeof(nmethod));
 162     if (relocation_size != 0)     tty->print_cr(" relocation     = %d", relocation_size);
 163     if (consts_size != 0)         tty->print_cr(" constants      = %d", consts_size);
 164     if (insts_size != 0)          tty->print_cr(" main code      = %d", insts_size);
 165     if (stub_size != 0)           tty->print_cr(" stub code      = %d", stub_size);
 166     if (oops_size != 0)           tty->print_cr(" oops           = %d", oops_size);
 167     if (metadata_size != 0)       tty->print_cr(" metadata       = %d", metadata_size);
 168     if (scopes_data_size != 0)    tty->print_cr(" scopes data    = %d", scopes_data_size);
 169     if (scopes_pcs_size != 0)     tty->print_cr(" scopes pcs     = %d", scopes_pcs_size);
 170     if (dependencies_size != 0)   tty->print_cr(" dependencies   = %d", dependencies_size);
 171     if (handler_table_size != 0)  tty->print_cr(" handler table  = %d", handler_table_size);
 172     if (nul_chk_table_size != 0)  tty->print_cr(" nul chk table  = %d", nul_chk_table_size);
 173 #if INCLUDE_JVMCI
 174     if (speculations_size != 0)   tty->print_cr(" speculations   = %d", speculations_size);
 175     if (jvmci_data_size != 0)     tty->print_cr(" JVMCI data     = %d", jvmci_data_size);
 176 #endif
 177   }
 178 };
 179 
 180 struct native_nmethod_stats_struct {
 181   int native_nmethod_count;
 182   int native_total_size;
 183   int native_relocation_size;
 184   int native_insts_size;
 185   int native_oops_size;
 186   int native_metadata_size;
 187   void note_native_nmethod(nmethod* nm) {
 188     native_nmethod_count += 1;
 189     native_total_size       += nm->size();
 190     native_relocation_size  += nm->relocation_size();
 191     native_insts_size       += nm->insts_size();
 192     native_oops_size        += nm->oops_size();
 193     native_metadata_size    += nm->metadata_size();
 194   }
 195   void print_native_nmethod_stats() {
 196     if (native_nmethod_count == 0)  return;
 197     tty->print_cr("Statistics for %d native nmethods:", native_nmethod_count);
 198     if (native_total_size != 0)       tty->print_cr(" N. total size  = %d", native_total_size);
 199     if (native_relocation_size != 0)  tty->print_cr(" N. relocation  = %d", native_relocation_size);
 200     if (native_insts_size != 0)       tty->print_cr(" N. main code   = %d", native_insts_size);
 201     if (native_oops_size != 0)        tty->print_cr(" N. oops        = %d", native_oops_size);
 202     if (native_metadata_size != 0)    tty->print_cr(" N. metadata    = %d", native_metadata_size);
 203   }
 204 };
 205 
 206 struct pc_nmethod_stats_struct {
 207   int pc_desc_resets;   // number of resets (= number of caches)
 208   int pc_desc_queries;  // queries to nmethod::find_pc_desc
 209   int pc_desc_approx;   // number of those which have approximate true
 210   int pc_desc_repeats;  // number of _pc_descs[0] hits
 211   int pc_desc_hits;     // number of LRU cache hits
 212   int pc_desc_tests;    // total number of PcDesc examinations
 213   int pc_desc_searches; // total number of quasi-binary search steps
 214   int pc_desc_adds;     // number of LUR cache insertions
 215 
 216   void print_pc_stats() {
 217     tty->print_cr("PcDesc Statistics:  %d queries, %.2f comparisons per query",
 218                   pc_desc_queries,
 219                   (double)(pc_desc_tests + pc_desc_searches)
 220                   / pc_desc_queries);
 221     tty->print_cr("  caches=%d queries=%d/%d, hits=%d+%d, tests=%d+%d, adds=%d",
 222                   pc_desc_resets,
 223                   pc_desc_queries, pc_desc_approx,
 224                   pc_desc_repeats, pc_desc_hits,
 225                   pc_desc_tests, pc_desc_searches, pc_desc_adds);
 226   }
 227 };
 228 
 229 #ifdef COMPILER1
 230 static java_nmethod_stats_struct c1_java_nmethod_stats;
 231 #endif
 232 #ifdef COMPILER2
 233 static java_nmethod_stats_struct c2_java_nmethod_stats;
 234 #endif
 235 #if INCLUDE_JVMCI
 236 static java_nmethod_stats_struct jvmci_java_nmethod_stats;
 237 #endif
 238 static java_nmethod_stats_struct unknown_java_nmethod_stats;
 239 
 240 static native_nmethod_stats_struct native_nmethod_stats;
 241 static pc_nmethod_stats_struct pc_nmethod_stats;
 242 
 243 static void note_java_nmethod(nmethod* nm) {
 244 #ifdef COMPILER1
 245   if (nm->is_compiled_by_c1()) {
 246     c1_java_nmethod_stats.note_nmethod(nm);
 247   } else
 248 #endif
 249 #ifdef COMPILER2
 250   if (nm->is_compiled_by_c2()) {
 251     c2_java_nmethod_stats.note_nmethod(nm);
 252   } else
 253 #endif
 254 #if INCLUDE_JVMCI
 255   if (nm->is_compiled_by_jvmci()) {
 256     jvmci_java_nmethod_stats.note_nmethod(nm);
 257   } else
 258 #endif
 259   {
 260     unknown_java_nmethod_stats.note_nmethod(nm);
 261   }
 262 }
 263 #endif // !PRODUCT
 264 
 265 //---------------------------------------------------------------------------------
 266 
 267 
 268 ExceptionCache::ExceptionCache(Handle exception, address pc, address handler) {
 269   assert(pc != NULL, "Must be non null");
 270   assert(exception.not_null(), "Must be non null");
 271   assert(handler != NULL, "Must be non null");
 272 
 273   _count = 0;
 274   _exception_type = exception->klass();
 275   _next = NULL;
 276   _purge_list_next = NULL;
 277 
 278   add_address_and_handler(pc,handler);
 279 }
 280 
 281 
 282 address ExceptionCache::match(Handle exception, address pc) {
 283   assert(pc != NULL,"Must be non null");
 284   assert(exception.not_null(),"Must be non null");
 285   if (exception->klass() == exception_type()) {
 286     return (test_address(pc));
 287   }
 288 
 289   return NULL;
 290 }
 291 
 292 
 293 bool ExceptionCache::match_exception_with_space(Handle exception) {
 294   assert(exception.not_null(),"Must be non null");
 295   if (exception->klass() == exception_type() && count() < cache_size) {
 296     return true;
 297   }
 298   return false;
 299 }
 300 
 301 
 302 address ExceptionCache::test_address(address addr) {
 303   int limit = count();
 304   for (int i = 0; i < limit; i++) {
 305     if (pc_at(i) == addr) {
 306       return handler_at(i);
 307     }
 308   }
 309   return NULL;
 310 }
 311 
 312 
 313 bool ExceptionCache::add_address_and_handler(address addr, address handler) {
 314   if (test_address(addr) == handler) return true;
 315 
 316   int index = count();
 317   if (index < cache_size) {
 318     set_pc_at(index, addr);
 319     set_handler_at(index, handler);
 320     increment_count();
 321     return true;
 322   }
 323   return false;
 324 }
 325 
 326 ExceptionCache* ExceptionCache::next() {
 327   return Atomic::load(&_next);
 328 }
 329 
 330 void ExceptionCache::set_next(ExceptionCache *ec) {
 331   Atomic::store(&_next, ec);
 332 }
 333 
 334 //-----------------------------------------------------------------------------
 335 
 336 
 337 // Helper used by both find_pc_desc methods.
 338 static inline bool match_desc(PcDesc* pc, int pc_offset, bool approximate) {
 339   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_tests);
 340   if (!approximate)
 341     return pc->pc_offset() == pc_offset;
 342   else
 343     return (pc-1)->pc_offset() < pc_offset && pc_offset <= pc->pc_offset();
 344 }
 345 
 346 void PcDescCache::reset_to(PcDesc* initial_pc_desc) {
 347   if (initial_pc_desc == NULL) {
 348     _pc_descs[0] = NULL; // native method; no PcDescs at all
 349     return;
 350   }
 351   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_resets);
 352   // reset the cache by filling it with benign (non-null) values
 353   assert(initial_pc_desc->pc_offset() < 0, "must be sentinel");
 354   for (int i = 0; i < cache_size; i++)
 355     _pc_descs[i] = initial_pc_desc;
 356 }
 357 
 358 PcDesc* PcDescCache::find_pc_desc(int pc_offset, bool approximate) {
 359   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_queries);
 360   NOT_PRODUCT(if (approximate) ++pc_nmethod_stats.pc_desc_approx);
 361 
 362   // Note: one might think that caching the most recently
 363   // read value separately would be a win, but one would be
 364   // wrong.  When many threads are updating it, the cache
 365   // line it's in would bounce between caches, negating
 366   // any benefit.
 367 
 368   // In order to prevent race conditions do not load cache elements
 369   // repeatedly, but use a local copy:
 370   PcDesc* res;
 371 
 372   // Step one:  Check the most recently added value.
 373   res = _pc_descs[0];
 374   if (res == NULL) return NULL;  // native method; no PcDescs at all
 375   if (match_desc(res, pc_offset, approximate)) {
 376     NOT_PRODUCT(++pc_nmethod_stats.pc_desc_repeats);
 377     return res;
 378   }
 379 
 380   // Step two:  Check the rest of the LRU cache.
 381   for (int i = 1; i < cache_size; ++i) {
 382     res = _pc_descs[i];
 383     if (res->pc_offset() < 0) break;  // optimization: skip empty cache
 384     if (match_desc(res, pc_offset, approximate)) {
 385       NOT_PRODUCT(++pc_nmethod_stats.pc_desc_hits);
 386       return res;
 387     }
 388   }
 389 
 390   // Report failure.
 391   return NULL;
 392 }
 393 
 394 void PcDescCache::add_pc_desc(PcDesc* pc_desc) {
 395   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_adds);
 396   // Update the LRU cache by shifting pc_desc forward.
 397   for (int i = 0; i < cache_size; i++)  {
 398     PcDesc* next = _pc_descs[i];
 399     _pc_descs[i] = pc_desc;
 400     pc_desc = next;
 401   }
 402 }
 403 
 404 // adjust pcs_size so that it is a multiple of both oopSize and
 405 // sizeof(PcDesc) (assumes that if sizeof(PcDesc) is not a multiple
 406 // of oopSize, then 2*sizeof(PcDesc) is)
 407 static int adjust_pcs_size(int pcs_size) {
 408   int nsize = align_up(pcs_size,   oopSize);
 409   if ((nsize % sizeof(PcDesc)) != 0) {
 410     nsize = pcs_size + sizeof(PcDesc);
 411   }
 412   assert((nsize % oopSize) == 0, "correct alignment");
 413   return nsize;
 414 }
 415 
 416 
 417 int nmethod::total_size() const {
 418   return
 419     consts_size()        +
 420     insts_size()         +
 421     stub_size()          +
 422     scopes_data_size()   +
 423     scopes_pcs_size()    +
 424     handler_table_size() +
 425     nul_chk_table_size();
 426 }
 427 




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