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