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