1 /*
   2  * Copyright (c) 2016, 2017, 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 #include "precompiled.hpp"
  25 
  26 #include "aot/aotCodeHeap.hpp"
  27 #include "aot/aotLoader.hpp"
  28 #include "gc/g1/heapRegion.hpp"
  29 #include "gc/shared/gcLocker.hpp"
  30 #include "interpreter/abstractInterpreter.hpp"
  31 #include "jvmci/compilerRuntime.hpp"
  32 #include "jvmci/jvmciRuntime.hpp"
  33 #include "oops/method.hpp"
  34 #include "runtime/os.hpp"
  35 #include "runtime/sharedRuntime.hpp"
  36 #include "runtime/vm_operations.hpp"
  37 
  38 bool AOTLib::_narrow_oop_shift_initialized = false;
  39 int  AOTLib::_narrow_oop_shift = 0;
  40 int  AOTLib::_narrow_klass_shift = 0;
  41 
  42 address AOTLib::load_symbol(const char *name) {
  43   address symbol = (address) os::dll_lookup(_dl_handle, name);
  44   if (symbol == NULL) {
  45     tty->print_cr("Shared file %s error: missing %s", _name, name);
  46     vm_exit(1);
  47   }
  48   return symbol;
  49 }
  50 
  51 Klass* AOTCodeHeap::get_klass_from_got(const char* klass_name, int klass_len, const Method* method) {
  52   AOTKlassData* klass_data = (AOTKlassData*)_lib->load_symbol(klass_name);
  53   Klass* k = (Klass*)_metaspace_got[klass_data->_got_index];
  54   if (k == NULL) {
  55     Thread* thread = Thread::current();
  56     k = lookup_klass(klass_name, klass_len, method, thread);
  57     // Note, exceptions are cleared.
  58     if (k == NULL) {
  59       fatal("Shared file %s error: klass %s should be resolved already", _lib->name(), klass_name);
  60       vm_exit(1);
  61     }
  62     _metaspace_got[klass_data->_got_index] = k;
  63   }
  64   return k;
  65 }
  66 
  67 Klass* AOTCodeHeap::lookup_klass(const char* name, int len, const Method* method, Thread* thread) {
  68   ResourceMark rm(thread);
  69   assert(method != NULL, "incorrect call parameter");
  70   methodHandle caller(thread, (Method*)method);
  71 
  72   // Use class loader of aot method.
  73   Handle loader(thread, caller->method_holder()->class_loader());
  74   Handle protection_domain(thread, caller->method_holder()->protection_domain());
  75 
  76   // Ignore wrapping L and ;
  77   if (name[0] == 'L') {
  78     assert(len > 2, "small name %s", name);
  79     name++;
  80     len -= 2;
  81   }
  82   TempNewSymbol sym = SymbolTable::probe(name, len);
  83   if (sym == NULL) {
  84     log_debug(aot, class, resolve)("Probe failed for AOT class %s", name);
  85     return NULL;
  86   }
  87   Klass* k = SystemDictionary::find_instance_or_array_klass(sym, loader, protection_domain, thread);
  88   assert(!thread->has_pending_exception(), "should not throw");
  89 
  90   if (k != NULL) {
  91     log_info(aot, class, resolve)("%s %s (lookup)", caller->method_holder()->external_name(), k->external_name());
  92   }
  93   return k;
  94 }
  95 
  96 void AOTLib::handle_config_error(const char* format, ...) {
  97   if (PrintAOT) {
  98     va_list ap;
  99     va_start(ap, format);
 100     tty->vprint_cr(format, ap);
 101     va_end(ap);
 102   }
 103   if (UseAOTStrictLoading) {
 104     vm_exit(1);
 105   }
 106   _valid = false;
 107 }
 108 
 109 void AOTLib::verify_flag(bool aot_flag, bool flag, const char* name) {
 110   if (_valid && aot_flag != flag) {
 111     handle_config_error("Shared file %s error: %s has different value '%s' from current '%s'", _name, name , (aot_flag ? "true" : "false"), (flag ? "true" : "false"));
 112   }
 113 }
 114 
 115 void AOTLib::verify_flag(int aot_flag, int flag, const char* name) {
 116   if (_valid && aot_flag != flag) {
 117     handle_config_error("Shared file %s error: %s has different value '%d' from current '%d'", _name, name , aot_flag, flag);
 118   }
 119 }
 120 
 121 void AOTLib::verify_config() {
 122   GrowableArray<AOTLib*>* libraries = AOTLoader::libraries();
 123   for (GrowableArrayIterator<AOTLib*> lib = libraries->begin(); lib != libraries->end(); ++lib) {
 124     if ((*lib)->_config == _config) {
 125       handle_config_error("AOT library %s already loaded.", (*lib)->_name);
 126       return;
 127     }
 128   }
 129 
 130   if (_header->_version != AOTHeader::AOT_SHARED_VERSION) {
 131     handle_config_error("Invalid version of the shared file %s. Expected %d but was %d", _name, _header->_version, AOTHeader::AOT_SHARED_VERSION);
 132     return;
 133   }
 134 
 135   const char* aot_jvm_version = (const char*)_header + _header->_jvm_version_offset + 2;
 136   if (strcmp(aot_jvm_version, VM_Version::jre_release_version()) != 0) {
 137     handle_config_error("JVM version '%s' recorded in the shared file %s does not match current version '%s'", aot_jvm_version, _name, VM_Version::jre_release_version());
 138     return;
 139   }
 140 
 141   // Debug VM has different layout of runtime and metadata structures
 142 #ifdef ASSERT
 143   verify_flag(_config->_debug_VM, true, "Debug VM version");
 144 #else
 145   verify_flag(!(_config->_debug_VM), true, "Product VM version");
 146 #endif
 147   // Check configuration size
 148   verify_flag(_config->_config_size, AOTConfiguration::CONFIG_SIZE, "AOT configuration size");
 149 
 150   // Check flags
 151   verify_flag(_config->_useCompressedOops, UseCompressedOops, "UseCompressedOops");
 152   verify_flag(_config->_useCompressedClassPointers, UseCompressedClassPointers, "UseCompressedClassPointers");
 153   verify_flag(_config->_useG1GC, UseG1GC, "UseG1GC");
 154   verify_flag(_config->_useCMSGC, UseConcMarkSweepGC, "UseConcMarkSweepGC");
 155   verify_flag(_config->_useTLAB, UseTLAB, "UseTLAB");
 156   verify_flag(_config->_useBiasedLocking, UseBiasedLocking, "UseBiasedLocking");
 157   verify_flag(_config->_objectAlignment, ObjectAlignmentInBytes, "ObjectAlignmentInBytes");
 158   verify_flag(_config->_contendedPaddingWidth, ContendedPaddingWidth, "ContendedPaddingWidth");
 159   verify_flag(_config->_fieldsAllocationStyle, FieldsAllocationStyle, "FieldsAllocationStyle");
 160   verify_flag(_config->_compactFields, CompactFields, "CompactFields");
 161   verify_flag(_config->_enableContended, EnableContended, "EnableContended");
 162   verify_flag(_config->_restrictContended, RestrictContended, "RestrictContended");
 163 
 164   if (!TieredCompilation && _config->_tieredAOT) {
 165     handle_config_error("Shared file %s error: Expected to run with tiered compilation on", _name);
 166   }
 167 
 168   // Shifts are static values which initialized by 0 until java heap initialization.
 169   // AOT libs are loaded before heap initialized so shift values are not set.
 170   // It is okay since ObjectAlignmentInBytes flag which defines shifts value is set before AOT libs are loaded.
 171   // Set shifts value based on first AOT library config.
 172   if (UseCompressedOops && _valid) {
 173     if (!_narrow_oop_shift_initialized) {
 174       _narrow_oop_shift = _config->_narrowOopShift;
 175       if (UseCompressedClassPointers) { // It is set only if UseCompressedOops is set
 176         _narrow_klass_shift = _config->_narrowKlassShift;
 177       }
 178       _narrow_oop_shift_initialized = true;
 179     } else {
 180       verify_flag(_config->_narrowOopShift, _narrow_oop_shift, "aot_config->_narrowOopShift");
 181       if (UseCompressedClassPointers) { // It is set only if UseCompressedOops is set
 182         verify_flag(_config->_narrowKlassShift, _narrow_klass_shift, "aot_config->_narrowKlassShift");
 183       }
 184     }
 185   }
 186 }
 187 
 188 AOTLib::~AOTLib() {
 189   free((void*) _name);
 190 }
 191 
 192 AOTCodeHeap::~AOTCodeHeap() {
 193   if (_classes != NULL) {
 194     FREE_C_HEAP_ARRAY(AOTClass, _classes);
 195   }
 196   if (_code_to_aot != NULL) {
 197     FREE_C_HEAP_ARRAY(CodeToAMethod, _code_to_aot);
 198   }
 199 }
 200 
 201 AOTLib::AOTLib(void* handle, const char* name, int dso_id) : _valid(true), _dl_handle(handle), _dso_id(dso_id) {
 202   _name = (const char*) strdup(name);
 203 
 204   // Verify that VM runs with the same parameters as AOT tool.
 205   _config = (AOTConfiguration*) load_symbol("JVM.config");
 206   _header = (AOTHeader*) load_symbol("JVM.header");
 207 
 208   verify_config();
 209 
 210   if (!_valid && PrintAOT) {
 211       tty->print("%7d ", (int) tty->time_stamp().milliseconds());
 212       tty->print_cr("%4d     skipped %s  aot library", _dso_id, _name);
 213   }
 214 }
 215 
 216 AOTCodeHeap::AOTCodeHeap(AOTLib* lib) :
 217     CodeHeap("CodeHeap 'AOT'", CodeBlobType::AOT), _lib(lib), _classes(NULL), _code_to_aot(NULL) {
 218   assert(_lib->is_valid(), "invalid library");
 219 
 220   _lib_symbols_initialized = false;
 221   _aot_id = 0;
 222 
 223   _class_count = _lib->header()->_class_count;
 224   _method_count = _lib->header()->_method_count;
 225 
 226   // Collect metaspace info: names -> address in .got section
 227   _metaspace_names = (const char*) _lib->load_symbol("JVM.meta.names");
 228   _method_metadata =     (address) _lib->load_symbol("JVM.meth.metadata");
 229   _methods_offsets =     (address) _lib->load_symbol("JVM.methods.offsets");
 230   _klasses_offsets =     (address) _lib->load_symbol("JVM.kls.offsets");
 231   _dependencies    =     (address) _lib->load_symbol("JVM.kls.dependencies");
 232   _code_space      =     (address) _lib->load_symbol("JVM.text");
 233 
 234   // First cell is number of elements.
 235   _metaspace_got      = (Metadata**) _lib->load_symbol("JVM.meta.got");
 236   _metaspace_got_size = _lib->header()->_metaspace_got_size;
 237 
 238   _metadata_got      = (Metadata**) _lib->load_symbol("JVM.metadata.got");
 239   _metadata_got_size = _lib->header()->_metadata_got_size;
 240 
 241   _oop_got      = (oop*) _lib->load_symbol("JVM.oop.got");
 242   _oop_got_size = _lib->header()->_oop_got_size;
 243 
 244   // Collect stubs info
 245   _stubs_offsets = (int*) _lib->load_symbol("JVM.stubs.offsets");
 246 
 247   // code segments table
 248   _code_segments = (address) _lib->load_symbol("JVM.code.segments");
 249 
 250   // method state
 251   _method_state = (jlong*) _lib->load_symbol("JVM.meth.state");
 252 
 253   // Create a table for mapping classes
 254   _classes = NEW_C_HEAP_ARRAY(AOTClass, _class_count, mtCode);
 255   memset(_classes, 0, _class_count * sizeof(AOTClass));
 256 
 257   // Create table for searching AOTCompiledMethod based on pc.
 258   _code_to_aot = NEW_C_HEAP_ARRAY(CodeToAMethod, _method_count, mtCode);
 259   memset(_code_to_aot, 0, _method_count * sizeof(CodeToAMethod));
 260 
 261   _low_boundary = _code_space;
 262   _memory.set_low_boundary((char *)_code_space);
 263   _memory.set_high_boundary((char *)_code_space);
 264   _memory.set_low((char *)_code_space);
 265   _memory.set_high((char *)_code_space);
 266 
 267   _segmap.set_low_boundary((char *)_code_segments);
 268   _segmap.set_low((char *)_code_segments);
 269 
 270   _log2_segment_size = exact_log2(_lib->config()->_codeSegmentSize);
 271 
 272   // Register aot stubs
 273   register_stubs();
 274 
 275   if (PrintAOT || (PrintCompilation && PrintAOT)) {
 276     tty->print("%7d ", (int) tty->time_stamp().milliseconds());
 277     tty->print_cr("%4d     loaded    %s  aot library", _lib->id(), _lib->name());
 278   }
 279 }
 280 
 281 void AOTCodeHeap::publish_aot(const methodHandle& mh, AOTMethodData* method_data, int code_id) {
 282   // The method may be explicitly excluded by the user.
 283   // Or Interpreter uses an intrinsic for this method.
 284   if (CompilerOracle::should_exclude(mh) || !AbstractInterpreter::can_be_compiled(mh)) {
 285     return;
 286   }
 287 
 288   address code = method_data->_code;
 289   const char* name = method_data->_name;
 290   aot_metadata* meta = method_data->_meta;
 291 
 292   if (meta->scopes_pcs_begin() == meta->scopes_pcs_end()) {
 293     // When the AOT compiler compiles something big we fail to generate metadata
 294     // in CodeInstaller::gather_metadata. In that case the scopes_pcs_begin == scopes_pcs_end.
 295     // In all successful cases we always have 2 entries of scope pcs.
 296     return;
 297   }
 298 
 299   jlong* state_adr = &_method_state[code_id];
 300   address metadata_table = method_data->_metadata_table;
 301   int metadata_size = method_data->_metadata_size;
 302   assert(code_id < _method_count, "sanity");
 303   _aot_id++;
 304 
 305 #ifdef ASSERT
 306   if (_aot_id > CIStop || _aot_id < CIStart) {
 307     // Skip compilation
 308     return;
 309   }
 310 #endif
 311   // Check one more time.
 312   if (_code_to_aot[code_id]._state == invalid) {
 313     return;
 314   }
 315   AOTCompiledMethod *aot = new AOTCompiledMethod(code, mh(), meta, metadata_table, metadata_size, state_adr, this, name, code_id, _aot_id);
 316   assert(_code_to_aot[code_id]._aot == NULL, "should be not initialized");
 317   _code_to_aot[code_id]._aot = aot; // Should set this first
 318   if (Atomic::cmpxchg(in_use, (jint*)&_code_to_aot[code_id]._state, not_set) != not_set) {
 319     _code_to_aot[code_id]._aot = NULL; // Clean
 320   } else { // success
 321     // Publish method
 322 #ifdef TIERED
 323     mh->set_aot_code(aot);
 324 #endif
 325     Method::set_code(mh, aot);
 326     if (PrintAOT || (PrintCompilation && PrintAOT)) {
 327       aot->print_on(tty, NULL);
 328     }
 329     // Publish oop only after we are visible to CompiledMethodIterator
 330     aot->set_oop(mh()->method_holder()->klass_holder());
 331   }
 332 }
 333 
 334 void AOTCodeHeap::link_primitive_array_klasses() {
 335   ResourceMark rm;
 336   for (int i = T_BOOLEAN; i <= T_CONFLICT; i++) {
 337     BasicType t = (BasicType)i;
 338     if (is_java_primitive(t)) {
 339       const Klass* arr_klass = Universe::typeArrayKlassObj(t);
 340       AOTKlassData* klass_data = (AOTKlassData*) os::dll_lookup(_lib->dl_handle(), arr_klass->signature_name());
 341       if (klass_data != NULL) {
 342         // Set both GOT cells, resolved and initialized klass pointers.
 343         // _got_index points to second cell - resolved klass pointer.
 344         _metaspace_got[klass_data->_got_index-1] = (Metadata*)arr_klass; // Initialized
 345         _metaspace_got[klass_data->_got_index  ] = (Metadata*)arr_klass; // Resolved
 346         if (PrintAOT) {
 347           tty->print_cr("[Found  %s  in  %s]", arr_klass->internal_name(), _lib->name());
 348         }
 349       }
 350     }
 351   }
 352 }
 353 
 354 void AOTCodeHeap::register_stubs() {
 355   int stubs_count = _stubs_offsets[0]; // contains number
 356   _stubs_offsets++;
 357   AOTMethodOffsets* stub_offsets = (AOTMethodOffsets*)_stubs_offsets;
 358   for (int i = 0; i < stubs_count; ++i) {
 359     const char* stub_name = _metaspace_names + stub_offsets[i]._name_offset;
 360     address entry = _code_space  + stub_offsets[i]._code_offset;
 361     aot_metadata* meta = (aot_metadata *) (_method_metadata + stub_offsets[i]._meta_offset);
 362     address metadata_table = (address)_metadata_got + stub_offsets[i]._metadata_got_offset;
 363     int metadata_size = stub_offsets[i]._metadata_got_size;
 364     int code_id = stub_offsets[i]._code_id;
 365     assert(code_id < _method_count, "sanity");
 366     jlong* state_adr = &_method_state[code_id];
 367     int len = build_u2_from((address)stub_name);
 368     stub_name += 2;
 369     char* full_name = NEW_C_HEAP_ARRAY(char, len+5, mtCode);
 370     if (full_name == NULL) { // No memory?
 371       break;
 372     }
 373     memcpy(full_name, "AOT ", 4);
 374     memcpy(full_name+4, stub_name, len);
 375     full_name[len+4] = 0;
 376     guarantee(_code_to_aot[code_id]._state != invalid, "stub %s can't be invalidated", full_name);
 377     AOTCompiledMethod* aot = new AOTCompiledMethod(entry, NULL, meta, metadata_table, metadata_size, state_adr, this, full_name, code_id, i);
 378     assert(_code_to_aot[code_id]._aot  == NULL, "should be not initialized");
 379     _code_to_aot[code_id]._aot  = aot;
 380     if (Atomic::cmpxchg(in_use, (jint*)&_code_to_aot[code_id]._state, not_set) != not_set) {
 381       fatal("stab '%s' code state is %d", full_name, _code_to_aot[code_id]._state);
 382     }
 383     // Adjust code buffer boundaries only for stubs because they are last in the buffer.
 384     adjust_boundaries(aot);
 385     if (PrintAOT && Verbose) {
 386       aot->print_on(tty, NULL);
 387     }
 388   }
 389 }
 390 
 391 #define SET_AOT_GLOBAL_SYMBOL_VALUE(AOTSYMNAME, AOTSYMTYPE, VMSYMVAL) \
 392   {                                                                   \
 393     AOTSYMTYPE * adr = (AOTSYMTYPE *) os::dll_lookup(_lib->dl_handle(), AOTSYMNAME);  \
 394     /* Check for a lookup error */                                    \
 395     guarantee(adr != NULL, "AOT Symbol not found %s", AOTSYMNAME);    \
 396     *adr = (AOTSYMTYPE) VMSYMVAL;                                     \
 397   }
 398 
 399 void AOTCodeHeap::link_graal_runtime_symbols()  {
 400     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_monitorenter", address, JVMCIRuntime::monitorenter);
 401     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_monitorexit", address, JVMCIRuntime::monitorexit);
 402     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_log_object", address, JVMCIRuntime::log_object);
 403     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_log_printf", address, JVMCIRuntime::log_printf);
 404     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_log_primitive", address, JVMCIRuntime::log_primitive);
 405     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_new_instance", address, JVMCIRuntime::new_instance);
 406     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_new_array", address, JVMCIRuntime::new_array);
 407     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_new_multi_array", address, JVMCIRuntime::new_multi_array);
 408     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_dynamic_new_array", address, JVMCIRuntime::dynamic_new_array);
 409     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_validate_object", address, JVMCIRuntime::validate_object);
 410     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_write_barrier_pre", address, JVMCIRuntime::write_barrier_pre);
 411     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_identity_hash_code", address, JVMCIRuntime::identity_hash_code);
 412     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_write_barrier_post", address, JVMCIRuntime::write_barrier_post);
 413     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_dynamic_new_instance", address, JVMCIRuntime::dynamic_new_instance);
 414     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_thread_is_interrupted", address, JVMCIRuntime::thread_is_interrupted);
 415     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_exception_handler_for_pc", address, JVMCIRuntime::exception_handler_for_pc);
 416     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_test_deoptimize_call_int", address, JVMCIRuntime::test_deoptimize_call_int);
 417     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_throw_and_post_jvmti_exception", address, JVMCIRuntime::throw_and_post_jvmti_exception);
 418     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_throw_klass_external_name_exception", address, JVMCIRuntime::throw_klass_external_name_exception);
 419     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_throw_class_cast_exception", address, JVMCIRuntime::throw_class_cast_exception);
 420     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_vm_message", address, JVMCIRuntime::vm_message);
 421     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_jvmci_runtime_vm_error", address, JVMCIRuntime::vm_error);
 422 }
 423 
 424 void AOTCodeHeap::link_shared_runtime_symbols() {
 425     SET_AOT_GLOBAL_SYMBOL_VALUE("_resolve_static_entry", address, SharedRuntime::get_resolve_static_call_stub());
 426     SET_AOT_GLOBAL_SYMBOL_VALUE("_resolve_virtual_entry", address, SharedRuntime::get_resolve_virtual_call_stub());
 427     SET_AOT_GLOBAL_SYMBOL_VALUE("_resolve_opt_virtual_entry", address, SharedRuntime::get_resolve_opt_virtual_call_stub());
 428     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_deopt_blob_unpack", address, SharedRuntime::deopt_blob()->unpack());
 429     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_deopt_blob_uncommon_trap", address, SharedRuntime::deopt_blob()->uncommon_trap());
 430     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_ic_miss_stub", address, SharedRuntime::get_ic_miss_stub());
 431     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_handle_wrong_method_stub", address, SharedRuntime::get_handle_wrong_method_stub());
 432     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_exception_handler_for_return_address", address, SharedRuntime::exception_handler_for_return_address);
 433     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_register_finalizer", address, SharedRuntime::register_finalizer);
 434     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_OSR_migration_end", address, SharedRuntime::OSR_migration_end);
 435     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_resolve_string_by_symbol", address, CompilerRuntime::resolve_string_by_symbol);
 436     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_resolve_klass_by_symbol", address, CompilerRuntime::resolve_klass_by_symbol);
 437     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_resolve_method_by_symbol_and_load_counters", address, CompilerRuntime::resolve_method_by_symbol_and_load_counters);
 438     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_initialize_klass_by_symbol", address, CompilerRuntime::initialize_klass_by_symbol);
 439     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_invocation_event", address, CompilerRuntime::invocation_event);
 440     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_backedge_event", address, CompilerRuntime::backedge_event);
 441 
 442     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_shared_runtime_dpow", address, SharedRuntime::dpow);
 443     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_shared_runtime_dexp", address, SharedRuntime::dexp);
 444     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_shared_runtime_dcos", address, SharedRuntime::dcos);
 445     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_shared_runtime_dsin", address, SharedRuntime::dsin);
 446     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_shared_runtime_dtan", address, SharedRuntime::dtan);
 447     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_shared_runtime_dlog", address, SharedRuntime::dlog);
 448     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_shared_runtime_dlog10", address, SharedRuntime::dlog10);
 449 }
 450 
 451 void AOTCodeHeap::link_stub_routines_symbols() {
 452     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jbyte_arraycopy", address, StubRoutines::_jbyte_arraycopy);
 453     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jshort_arraycopy", address, StubRoutines::_jshort_arraycopy);
 454     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jint_arraycopy", address, StubRoutines::_jint_arraycopy);
 455     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jlong_arraycopy", address, StubRoutines::_jlong_arraycopy);
 456     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_oop_arraycopy", address, StubRoutines::_oop_arraycopy);
 457     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_oop_arraycopy_uninit", address, StubRoutines::_oop_arraycopy_uninit);
 458 
 459     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jbyte_disjoint_arraycopy", address, StubRoutines::_jbyte_disjoint_arraycopy);
 460     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jshort_disjoint_arraycopy", address, StubRoutines::_jshort_disjoint_arraycopy);
 461     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jint_disjoint_arraycopy", address, StubRoutines::_jint_disjoint_arraycopy);
 462     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_jlong_disjoint_arraycopy", address, StubRoutines::_jlong_disjoint_arraycopy);
 463     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_oop_disjoint_arraycopy", address, StubRoutines::_oop_disjoint_arraycopy);
 464     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_oop_disjoint_arraycopy_uninit", address, StubRoutines::_oop_disjoint_arraycopy_uninit);
 465 
 466     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jbyte_arraycopy", address, StubRoutines::_arrayof_jbyte_arraycopy);
 467     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jshort_arraycopy", address, StubRoutines::_arrayof_jshort_arraycopy);
 468     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jint_arraycopy", address, StubRoutines::_arrayof_jint_arraycopy);
 469     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jlong_arraycopy", address, StubRoutines::_arrayof_jlong_arraycopy);
 470     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_oop_arraycopy", address, StubRoutines::_arrayof_oop_arraycopy);
 471     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_oop_arraycopy_uninit", address, StubRoutines::_arrayof_oop_arraycopy_uninit);
 472 
 473     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jbyte_disjoint_arraycopy", address, StubRoutines::_arrayof_jbyte_disjoint_arraycopy);
 474     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jshort_disjoint_arraycopy", address, StubRoutines::_arrayof_jshort_disjoint_arraycopy);
 475     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jint_disjoint_arraycopy", address, StubRoutines::_arrayof_jint_disjoint_arraycopy);
 476     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_jlong_disjoint_arraycopy", address, StubRoutines::_arrayof_jlong_disjoint_arraycopy);
 477     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_oop_disjoint_arraycopy", address, StubRoutines::_arrayof_oop_disjoint_arraycopy);
 478     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_arrayof_oop_disjoint_arraycopy_uninit", address, StubRoutines::_arrayof_oop_disjoint_arraycopy_uninit);
 479 
 480     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_checkcast_arraycopy", address, StubRoutines::_checkcast_arraycopy);
 481 
 482     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_aescrypt_encryptBlock", address, StubRoutines::_aescrypt_encryptBlock);
 483     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_aescrypt_decryptBlock", address, StubRoutines::_aescrypt_decryptBlock);
 484     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_cipherBlockChaining_encryptAESCrypt", address, StubRoutines::_cipherBlockChaining_encryptAESCrypt);
 485     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_cipherBlockChaining_decryptAESCrypt", address, StubRoutines::_cipherBlockChaining_decryptAESCrypt);
 486     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_update_bytes_crc32", address, StubRoutines::_updateBytesCRC32);
 487     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_crc_table_adr", address, StubRoutines::_crc_table_adr);
 488 
 489 
 490     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_sha1_implCompress", address, StubRoutines::_sha1_implCompress);
 491     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_sha1_implCompressMB", address, StubRoutines::_sha1_implCompressMB);
 492     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_sha256_implCompress", address, StubRoutines::_sha256_implCompress);
 493     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_sha256_implCompressMB", address, StubRoutines::_sha256_implCompressMB);
 494     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_sha512_implCompress", address, StubRoutines::_sha512_implCompress);
 495     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_sha512_implCompressMB", address, StubRoutines::_sha512_implCompressMB);
 496     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_multiplyToLen", address, StubRoutines::_multiplyToLen);
 497 
 498     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_counterMode_AESCrypt", address, StubRoutines::_counterMode_AESCrypt);
 499     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_ghash_processBlocks", address, StubRoutines::_ghash_processBlocks);
 500     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_crc32c_table_addr", address, StubRoutines::_crc32c_table_addr);
 501     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_updateBytesCRC32C", address, StubRoutines::_updateBytesCRC32C);
 502     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_updateBytesAdler32", address, StubRoutines::_updateBytesAdler32);
 503     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_squareToLen", address, StubRoutines::_squareToLen);
 504     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_mulAdd", address, StubRoutines::_mulAdd);
 505     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_montgomeryMultiply",  address, StubRoutines::_montgomeryMultiply);
 506     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_montgomerySquare", address, StubRoutines::_montgomerySquare);
 507     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_vectorizedMismatch", address, StubRoutines::_vectorizedMismatch);
 508 
 509     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_stub_routines_throw_delayed_StackOverflowError_entry", address, StubRoutines::_throw_delayed_StackOverflowError_entry);
 510 
 511 }
 512 
 513 void AOTCodeHeap::link_os_symbols() {
 514     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_os_javaTimeMillis", address, os::javaTimeMillis);
 515     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_os_javaTimeNanos", address, os::javaTimeNanos);
 516 }
 517 
 518 /*
 519  * Link any global symbols in precompiled DSO with dlopen() _dl_handle
 520  * dso_handle.
 521  */
 522 
 523 void AOTCodeHeap::link_global_lib_symbols() {
 524   if (!_lib_symbols_initialized) {
 525     _lib_symbols_initialized = true;
 526 
 527     CollectedHeap* heap = Universe::heap();
 528     CardTableModRefBS* ct = (CardTableModRefBS*)(heap->barrier_set());
 529     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_card_table_address", address, ct->byte_map_base);
 530     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_heap_top_address", address, (heap->supports_inline_contig_alloc() ? heap->top_addr() : NULL));
 531     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_heap_end_address", address, (heap->supports_inline_contig_alloc() ? heap->end_addr() : NULL));
 532     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_polling_page", address, os::get_polling_page());
 533     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_narrow_klass_base_address", address, Universe::narrow_klass_base());
 534     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_log_of_heap_region_grain_bytes", int, HeapRegion::LogOfHRGrainBytes);
 535     SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_inline_contiguous_allocation_supported", bool, heap->supports_inline_contig_alloc());
 536     link_shared_runtime_symbols();
 537     link_stub_routines_symbols();
 538     link_os_symbols();
 539     link_graal_runtime_symbols();
 540 
 541     // Link primitive array klasses.
 542     link_primitive_array_klasses();
 543   }
 544 }
 545 
 546 #ifndef PRODUCT
 547 int AOTCodeHeap::klasses_seen = 0;
 548 int AOTCodeHeap::aot_klasses_found = 0;
 549 int AOTCodeHeap::aot_klasses_fp_miss = 0;
 550 int AOTCodeHeap::aot_klasses_cl_miss = 0;
 551 int AOTCodeHeap::aot_methods_found = 0;
 552 
 553 void AOTCodeHeap::print_statistics() {
 554   tty->print_cr("Classes seen: %d  AOT classes found: %d  AOT methods found: %d", klasses_seen, aot_klasses_found, aot_methods_found);
 555   tty->print_cr("AOT fingerprint mismatches: %d  AOT class loader mismatches: %d", aot_klasses_fp_miss, aot_klasses_cl_miss);
 556 }
 557 #endif
 558 
 559 Method* AOTCodeHeap::find_method(KlassHandle klass, Thread* thread, const char* method_name) {
 560   int method_name_len = build_u2_from((address)method_name);
 561   method_name += 2;
 562   const char* signature_name = method_name + method_name_len;
 563   int signature_name_len = build_u2_from((address)signature_name);
 564   signature_name += 2;
 565   // The class should have been loaded so the method and signature should already be
 566   // in the symbol table.  If they're not there, the method doesn't exist.
 567   TempNewSymbol name = SymbolTable::probe(method_name, method_name_len);
 568   TempNewSymbol signature = SymbolTable::probe(signature_name, signature_name_len);
 569 
 570   Method* m;
 571   if (name == NULL || signature == NULL) {
 572     m = NULL;
 573   } else if (name == vmSymbols::object_initializer_name() ||
 574              name == vmSymbols::class_initializer_name()) {
 575     // Never search superclasses for constructors
 576     if (klass->is_instance_klass()) {
 577       m = InstanceKlass::cast(klass())->find_method(name, signature);
 578     } else {
 579       m = NULL;
 580     }
 581   } else {
 582     m = klass->lookup_method(name, signature);
 583     if (m == NULL && klass->is_instance_klass()) {
 584       m = InstanceKlass::cast(klass())->lookup_method_in_ordered_interfaces(name, signature);
 585     }
 586   }
 587   if (m == NULL) {
 588     // Fatal error because we assume classes and methods should not be changed since aot compilation.
 589     const char* klass_name = klass->external_name();
 590     int klass_len = (int)strlen(klass_name);
 591     char* meta_name = NEW_RESOURCE_ARRAY(char, klass_len + 1 + method_name_len + signature_name_len + 1);
 592     memcpy(meta_name, klass_name, klass_len);
 593     meta_name[klass_len] = '.';
 594     memcpy(&meta_name[klass_len + 1], method_name, method_name_len);
 595     memcpy(&meta_name[klass_len + 1 + method_name_len], signature_name, signature_name_len);
 596     meta_name[klass_len + 1 + method_name_len + signature_name_len] = '\0';
 597     Handle exception = Exceptions::new_exception(thread, vmSymbols::java_lang_NoSuchMethodError(), meta_name);
 598     java_lang_Throwable::print(exception, tty);
 599     tty->cr();
 600     java_lang_Throwable::print_stack_trace(exception(), tty);
 601     tty->cr();
 602     fatal("Failed to find method '%s'", meta_name);
 603   }
 604   NOT_PRODUCT( aot_methods_found++; )
 605   return m;
 606 }
 607 
 608 AOTKlassData* AOTCodeHeap::find_klass(InstanceKlass* ik) {
 609   ResourceMark rm;
 610   AOTKlassData* klass_data = (AOTKlassData*) os::dll_lookup(_lib->dl_handle(), ik->signature_name());
 611   return klass_data;
 612 }
 613 
 614 bool AOTCodeHeap::is_dependent_method(Klass* dependee, AOTCompiledMethod* aot) {
 615   InstanceKlass *dependee_ik = InstanceKlass::cast(dependee);
 616   AOTKlassData* klass_data = find_klass(dependee_ik);
 617   if (klass_data == NULL) {
 618     return false; // no AOT records for this class - no dependencies
 619   }
 620   if (!dependee_ik->has_passed_fingerprint_check()) {
 621     return false; // different class
 622   }
 623 
 624   int methods_offset = klass_data->_dependent_methods_offset;
 625   if (methods_offset >= 0) {
 626     address methods_cnt_adr = _dependencies + methods_offset;
 627     int methods_cnt = *(int*)methods_cnt_adr;
 628     int* indexes = (int*)(methods_cnt_adr + 4);
 629     for (int i = 0; i < methods_cnt; ++i) {
 630       int code_id = indexes[i];
 631       if (_code_to_aot[code_id]._aot == aot) {
 632         return true; // found dependent method
 633       }
 634     }
 635   }
 636   return false;
 637 }
 638 
 639 void AOTCodeHeap::sweep_dependent_methods(AOTKlassData* klass_data) {
 640   // Make dependent methods non_entrant forever.
 641   int methods_offset = klass_data->_dependent_methods_offset;
 642   if (methods_offset >= 0) {
 643     int marked = 0;
 644     address methods_cnt_adr = _dependencies + methods_offset;
 645     int methods_cnt = *(int*)methods_cnt_adr;
 646     int* indexes = (int*)(methods_cnt_adr + 4);
 647     for (int i = 0; i < methods_cnt; ++i) {
 648       int code_id = indexes[i];
 649       // Invalidate aot code.
 650       if (Atomic::cmpxchg(invalid, (jint*)&_code_to_aot[code_id]._state, not_set) != not_set) {
 651         if (_code_to_aot[code_id]._state == in_use) {
 652           AOTCompiledMethod* aot = _code_to_aot[code_id]._aot;
 653           assert(aot != NULL, "aot should be set");
 654           if (!aot->is_runtime_stub()) { // Something is wrong - should not invalidate stubs.
 655             aot->mark_for_deoptimization(false);
 656             marked++;
 657           }
 658         }
 659       }
 660     }
 661     if (marked > 0) {
 662       VM_Deoptimize op;
 663       VMThread::execute(&op);
 664     }
 665   }
 666 }
 667 
 668 bool AOTCodeHeap::load_klass_data(instanceKlassHandle kh, Thread* thread) {
 669   ResourceMark rm;
 670 
 671   NOT_PRODUCT( klasses_seen++; )
 672 
 673   AOTKlassData* klass_data = find_klass(kh());
 674   if (klass_data == NULL) {
 675     return false;
 676   }
 677 
 678   if (!kh->has_passed_fingerprint_check()) {
 679     NOT_PRODUCT( aot_klasses_fp_miss++; )
 680     log_trace(aot, class, fingerprint)("class  %s%s  has bad fingerprint in  %s tid=" INTPTR_FORMAT,
 681                                    kh->internal_name(), kh->is_shared() ? " (shared)" : "",
 682                                    _lib->name(), p2i(thread));
 683     sweep_dependent_methods(klass_data);
 684     return false;
 685   }
 686 
 687   if (kh->has_been_redefined()) {
 688     log_trace(aot, class, load)("class  %s%s in %s  has been redefined tid=" INTPTR_FORMAT,
 689                                    kh->internal_name(), kh->is_shared() ? " (shared)" : "",
 690                                    _lib->name(), p2i(thread));
 691     sweep_dependent_methods(klass_data);
 692     return false;
 693   }
 694 
 695   assert(klass_data->_class_id < _class_count, "invalid class id");
 696   AOTClass* aot_class = &_classes[klass_data->_class_id];
 697   if (aot_class->_classloader != NULL && aot_class->_classloader != kh->class_loader_data()) {
 698     log_trace(aot, class, load)("class  %s  in  %s already loaded for classloader %p vs %p tid=" INTPTR_FORMAT,
 699                              kh->internal_name(), _lib->name(), aot_class->_classloader, kh->class_loader_data(), p2i(thread));
 700     NOT_PRODUCT( aot_klasses_cl_miss++; )
 701     return false;
 702   }
 703 
 704   NOT_PRODUCT( aot_klasses_found++; )
 705 
 706   log_trace(aot, class, load)("found  %s  in  %s for classloader %p tid=" INTPTR_FORMAT, kh->internal_name(), _lib->name(), kh->class_loader_data(), p2i(thread));
 707 
 708   aot_class->_classloader = kh->class_loader_data();
 709   // Set klass's Resolve (second) got cell.
 710   _metaspace_got[klass_data->_got_index] = kh();
 711 
 712   // Initialize global symbols of the DSO to the correspondingVM symbol values.
 713   link_global_lib_symbols();
 714 
 715   int methods_offset = klass_data->_compiled_methods_offset;
 716   if (methods_offset >= 0) {
 717     address methods_cnt_adr = _methods_offsets + methods_offset;
 718     int methods_cnt = *(int*)methods_cnt_adr;
 719     // Collect data about compiled methods
 720     AOTMethodData* methods_data = NEW_RESOURCE_ARRAY(AOTMethodData, methods_cnt);
 721     AOTMethodOffsets* methods_offsets = (AOTMethodOffsets*)(methods_cnt_adr + 4);
 722     for (int i = 0; i < methods_cnt; ++i) {
 723       AOTMethodOffsets* method_offsets = &methods_offsets[i];
 724       int code_id = method_offsets->_code_id;
 725       if (_code_to_aot[code_id]._state == invalid) {
 726         continue; // skip AOT methods slots which have been invalidated
 727       }
 728       AOTMethodData* method_data = &methods_data[i];
 729       const char* aot_name = _metaspace_names + method_offsets->_name_offset;
 730       method_data->_name = aot_name;
 731       method_data->_code = _code_space  + method_offsets->_code_offset;
 732       method_data->_meta = (aot_metadata*)(_method_metadata + method_offsets->_meta_offset);
 733       method_data->_metadata_table = (address)_metadata_got + method_offsets->_metadata_got_offset;
 734       method_data->_metadata_size  = method_offsets->_metadata_got_size;
 735       // aot_name format: "<u2_size>Ljava/lang/ThreadGroup;<u2_size>addUnstarted<u2_size>()V"
 736       int klass_len = build_u2_from((address)aot_name);
 737       const char* method_name = aot_name + 2 + klass_len;
 738       Method* m = AOTCodeHeap::find_method(kh, thread, method_name);
 739       methodHandle mh(thread, m);
 740       if (mh->code() != NULL) { // Does it have already compiled code?
 741         continue; // Don't overwrite
 742       }
 743       publish_aot(mh, method_data, code_id);
 744     }
 745   }
 746   return true;
 747 }
 748 
 749 AOTCompiledMethod* AOTCodeHeap::next_in_use_at(int start) const {
 750   for (int index = start; index < _method_count; index++) {
 751     if (_code_to_aot[index]._state != in_use) {
 752       continue; // Skip uninitialized entries.
 753     }
 754     AOTCompiledMethod* aot = _code_to_aot[index]._aot;
 755     return aot;
 756   }
 757   return NULL;
 758 }
 759 
 760 void* AOTCodeHeap::first() const {
 761   return next_in_use_at(0);
 762 }
 763 
 764 void* AOTCodeHeap::next(void* p) const {
 765   AOTCompiledMethod *aot = (AOTCompiledMethod *)p;
 766   int next_index = aot->method_index() + 1;
 767   assert(next_index <= _method_count, "");
 768   if (next_index == _method_count) {
 769     return NULL;
 770   }
 771   return next_in_use_at(next_index);
 772 }
 773 
 774 void* AOTCodeHeap::find_start(void* p) const {
 775   if (!contains(p)) {
 776     return NULL;
 777   }
 778   size_t offset = pointer_delta(p, low_boundary(), 1);
 779   // Use segments table
 780   size_t seg_idx = offset / _lib->config()->_codeSegmentSize;
 781   if ((int)(_code_segments[seg_idx]) == 0xff) {
 782     return NULL;
 783   }
 784   while (_code_segments[seg_idx] > 0) {
 785     seg_idx -= (int)_code_segments[seg_idx];
 786   }
 787   int code_offset = (int)seg_idx * _lib->config()->_codeSegmentSize;
 788   int aot_index = *(int*)(_code_space + code_offset);
 789   AOTCompiledMethod* aot = _code_to_aot[aot_index]._aot;
 790   assert(aot != NULL, "should find registered aot method");
 791   return aot;
 792 }
 793 
 794 AOTCompiledMethod* AOTCodeHeap::find_aot(address p) const {
 795   assert(contains(p), "should be here");
 796   return (AOTCompiledMethod *)find_start(p);
 797 }
 798 
 799 CodeBlob* AOTCodeHeap::find_blob_unsafe(void* start) const {
 800   return (CodeBlob*)AOTCodeHeap::find_start(start);
 801 }
 802 
 803 void AOTCodeHeap::oops_do(OopClosure* f) {
 804   for (int i = 0; i < _oop_got_size; i++) {
 805     oop* p = &_oop_got[i];
 806     if (*p == NULL)  continue;  // skip non-oops
 807     f->do_oop(p);
 808   }
 809   for (int index = 0; index < _method_count; index++) {
 810     if (_code_to_aot[index]._state != in_use) {
 811       continue; // Skip uninitialized entries.
 812     }
 813     AOTCompiledMethod* aot = _code_to_aot[index]._aot;
 814     aot->do_oops(f);
 815   }
 816 }
 817 
 818 // Yes, this is faster than going through the relocations,
 819 // but there are two problems:
 820 // 1) GOT slots are sometimes patched with non-Metadata values
 821 // 2) We don't want to scan metadata for dead methods
 822 // Unfortunately we don't know if the metadata belongs to
 823 // live aot methods or not, so process them all.  If this
 824 // is for mark_on_stack, some old methods may stick around
 825 // forever instead of getting cleaned up.
 826 void AOTCodeHeap::got_metadata_do(void f(Metadata*)) {
 827   for (int i = 1; i < _metaspace_got_size; i++) {
 828     Metadata** p = &_metaspace_got[i];
 829     Metadata* md = *p;
 830     if (md == NULL)  continue;  // skip non-oops
 831     intptr_t meta = (intptr_t)md;
 832     if (meta == -1)  continue;  // skip non-oops
 833     if (Metaspace::contains(md)) {
 834       f(md);
 835     }
 836   }
 837   for (int i = 1; i < _metadata_got_size; i++) {
 838     Metadata** p = &_metadata_got[i];
 839     Metadata* md = *p;
 840     intptr_t meta = (intptr_t)md;
 841     if ((meta & 1) == 1) {
 842       // already resolved
 843       md = (Metadata*)(meta & ~1);
 844     } else {
 845       continue;
 846     }
 847     if (md == NULL)  continue;  // skip non-oops
 848     if (Metaspace::contains(md)) {
 849       f(md);
 850     }
 851   }
 852 }
 853 
 854 void AOTCodeHeap::cleanup_inline_caches() {
 855   for (int index = 0; index < _method_count; index++) {
 856     if (_code_to_aot[index]._state != in_use) {
 857       continue; // Skip uninitialized entries.
 858     }
 859     AOTCompiledMethod* aot = _code_to_aot[index]._aot;
 860     aot->cleanup_inline_caches();
 861   }
 862 }
 863 
 864 #ifdef ASSERT
 865 int AOTCodeHeap::verify_icholder_relocations() {
 866   int count = 0;
 867   for (int index = 0; index < _method_count; index++) {
 868     if (_code_to_aot[index]._state != in_use) {
 869       continue; // Skip uninitialized entries.
 870     }
 871     AOTCompiledMethod* aot = _code_to_aot[index]._aot;
 872     count += aot->verify_icholder_relocations();
 873   }
 874   return count;
 875 }
 876 #endif
 877 
 878 void AOTCodeHeap::flush_evol_dependents_on(instanceKlassHandle dependee) {
 879   for (int index = 0; index < _method_count; index++) {
 880     if (_code_to_aot[index]._state != in_use) {
 881       continue; // Skip uninitialized entries.
 882     }
 883     AOTCompiledMethod* aot = _code_to_aot[index]._aot;
 884     aot->flush_evol_dependents_on(dependee);
 885   }
 886 }
 887 
 888 void AOTCodeHeap::metadata_do(void f(Metadata*)) {
 889   for (int index = 0; index < _method_count; index++) {
 890     if (_code_to_aot[index]._state != in_use) {
 891       continue; // Skip uninitialized entries.
 892     }
 893     AOTCompiledMethod* aot = _code_to_aot[index]._aot;
 894     if (aot->_is_alive()) {
 895       aot->metadata_do(f);
 896     }
 897   }
 898 #if 0
 899   // With the marking above, this call doesn't seem to be needed
 900   got_metadata_do(f);
 901 #endif
 902 }