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