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