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