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