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