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