1 /*
   2  * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "cds/aotCacheAccess.hpp"
  26 #include "cds/aotConstantPoolResolver.hpp"
  27 #include "cds/cdsConfig.hpp"
  28 #include "cds/heapShared.hpp"
  29 #include "ci/ciConstant.hpp"
  30 #include "ci/ciEnv.hpp"
  31 #include "ci/ciField.hpp"
  32 #include "ci/ciInstance.hpp"
  33 #include "ci/ciInstanceKlass.hpp"
  34 #include "ci/ciMethod.hpp"
  35 #include "ci/ciNullObject.hpp"
  36 #include "ci/ciReplay.hpp"
  37 #include "ci/ciSymbols.hpp"
  38 #include "ci/ciUtilities.inline.hpp"
  39 #include "classfile/javaClasses.hpp"
  40 #include "classfile/javaClasses.inline.hpp"
  41 #include "classfile/systemDictionary.hpp"
  42 #include "classfile/vmClasses.hpp"
  43 #include "classfile/vmSymbols.hpp"
  44 #include "code/aotCodeCache.hpp"
  45 #include "code/codeCache.hpp"
  46 #include "code/scopeDesc.hpp"
  47 #include "compiler/compilationLog.hpp"
  48 #include "compiler/compilationPolicy.hpp"
  49 #include "compiler/compileBroker.hpp"
  50 #include "compiler/compileLog.hpp"
  51 #include "compiler/compilerEvent.hpp"
  52 #include "compiler/compileTask.hpp"
  53 #include "compiler/disassembler.hpp"
  54 #include "gc/shared/barrierSetNMethod.hpp"
  55 #include "gc/shared/collectedHeap.inline.hpp"
  56 #include "interpreter/bytecodeStream.hpp"
  57 #include "interpreter/linkResolver.hpp"
  58 #include "jfr/jfrEvents.hpp"
  59 #include "jvm.h"
  60 #include "logging/log.hpp"
  61 #include "memory/allocation.inline.hpp"
  62 #include "memory/oopFactory.hpp"
  63 #include "memory/resourceArea.hpp"
  64 #include "memory/universe.hpp"
  65 #include "oops/constantPool.inline.hpp"
  66 #include "oops/cpCache.inline.hpp"
  67 #include "oops/method.inline.hpp"
  68 #include "oops/methodData.hpp"
  69 #include "oops/objArrayKlass.hpp"
  70 #include "oops/objArrayOop.inline.hpp"
  71 #include "oops/oop.inline.hpp"
  72 #include "oops/resolvedIndyEntry.hpp"
  73 #include "oops/symbolHandle.hpp"
  74 #include "oops/trainingData.hpp"
  75 #include "prims/jvmtiExport.hpp"
  76 #include "prims/methodHandles.hpp"
  77 #include "runtime/fieldDescriptor.inline.hpp"
  78 #include "runtime/flags/flagSetting.hpp"
  79 #include "runtime/handles.inline.hpp"
  80 #include "runtime/init.hpp"
  81 #include "runtime/javaThread.hpp"
  82 #include "runtime/jniHandles.inline.hpp"
  83 #include "runtime/reflection.hpp"
  84 #include "runtime/safepointVerifiers.hpp"
  85 #include "runtime/sharedRuntime.hpp"
  86 #include "utilities/dtrace.hpp"
  87 #include "utilities/macros.hpp"
  88 #ifdef COMPILER1
  89 #include "c1/c1_Runtime1.hpp"
  90 #endif
  91 #ifdef COMPILER2
  92 #include "opto/runtime.hpp"
  93 #endif
  94 
  95 // ciEnv
  96 //
  97 // This class is the top level broker for requests from the compiler
  98 // to the VM.
  99 
 100 ciObject*              ciEnv::_null_object_instance;
 101 
 102 #define VM_CLASS_DEFN(name, ignore_s) ciInstanceKlass* ciEnv::_##name = nullptr;
 103 VM_CLASSES_DO(VM_CLASS_DEFN)
 104 #undef VM_CLASS_DEFN
 105 
 106 ciSymbol*        ciEnv::_unloaded_cisymbol = nullptr;
 107 ciInstanceKlass* ciEnv::_unloaded_ciinstance_klass = nullptr;
 108 ciObjArrayKlass* ciEnv::_unloaded_ciobjarrayklass = nullptr;
 109 
 110 #ifndef PRODUCT
 111 static bool firstEnv = true;
 112 #endif /* PRODUCT */
 113 
 114 // ------------------------------------------------------------------
 115 // ciEnv::ciEnv
 116 ciEnv::ciEnv(CompileTask* task)
 117   : _ciEnv_arena(mtCompiler, Arena::Tag::tag_cienv) {
 118   VM_ENTRY_MARK;
 119 
 120   // Set up ciEnv::current immediately, for the sake of ciObjectFactory, etc.
 121   thread->set_env(this);
 122   assert(ciEnv::current() == this, "sanity");
 123 
 124   _oop_recorder = nullptr;
 125   _debug_info = nullptr;
 126   _dependencies = nullptr;
 127   _inc_decompile_count_on_failure = true;
 128   _compilable = MethodCompilable;
 129   _break_at_compile = false;
 130   _compiler_data = nullptr;
 131 #ifndef PRODUCT
 132   assert(!firstEnv, "not initialized properly");
 133 #endif /* !PRODUCT */
 134 
 135   _num_inlined_bytecodes = 0;
 136   assert(task == nullptr || thread->task() == task, "sanity");
 137   if (task != nullptr) {
 138     task->mark_started(os::elapsed_counter());
 139   }
 140   _task = task;
 141   _log = nullptr;
 142 
 143   // Temporary buffer for creating symbols and such.
 144   _name_buffer = nullptr;
 145   _name_buffer_len = 0;
 146 
 147   _arena   = &_ciEnv_arena;
 148   _factory = new (_arena) ciObjectFactory(_arena, 128);
 149 
 150   // Preload commonly referenced system ciObjects.
 151 
 152   // During VM initialization, these instances have not yet been created.
 153   // Assertions ensure that these instances are not accessed before
 154   // their initialization.
 155 
 156   assert(Universe::is_fully_initialized(), "should be complete");
 157 
 158   oop o = Universe::null_ptr_exception_instance();
 159   assert(o != nullptr, "should have been initialized");
 160   _NullPointerException_instance = get_object(o)->as_instance();
 161   o = Universe::arithmetic_exception_instance();
 162   assert(o != nullptr, "should have been initialized");
 163   _ArithmeticException_instance = get_object(o)->as_instance();
 164   o = Universe::array_index_out_of_bounds_exception_instance();
 165   assert(o != nullptr, "should have been initialized");
 166   _ArrayIndexOutOfBoundsException_instance = get_object(o)->as_instance();
 167   o = Universe::array_store_exception_instance();
 168   assert(o != nullptr, "should have been initialized");
 169   _ArrayStoreException_instance = get_object(o)->as_instance();
 170   o = Universe::class_cast_exception_instance();
 171   assert(o != nullptr, "should have been initialized");
 172   _ClassCastException_instance = get_object(o)->as_instance();
 173 
 174   _the_null_string = nullptr;
 175   _the_min_jint_string = nullptr;
 176 
 177   _jvmti_redefinition_count = 0;
 178   _jvmti_can_hotswap_or_post_breakpoint = false;
 179   _jvmti_can_access_local_variables = false;
 180   _jvmti_can_post_on_exceptions = false;
 181   _jvmti_can_pop_frame = false;
 182 
 183   _dyno_klasses = nullptr;
 184   _dyno_locs = nullptr;
 185   _dyno_name[0] = '\0';
 186 }
 187 
 188 // Record components of a location descriptor string.  Components are appended by the constructor and
 189 // removed by the destructor, like a stack, so scope matters.  These location descriptors are used to
 190 // locate dynamic classes, and terminate at a Method* or oop field associated with dynamic/hidden class.
 191 //
 192 // Example use:
 193 //
 194 // {
 195 //   RecordLocation fp(this, "field1");
 196 //   // location: "field1"
 197 //   { RecordLocation fp(this, " field2"); // location: "field1 field2" }
 198 //   // location: "field1"
 199 //   { RecordLocation fp(this, " field3"); // location: "field1 field3" }
 200 //   // location: "field1"
 201 // }
 202 // // location: ""
 203 //
 204 // Examples of actual locations
 205 // @bci compiler/ciReplay/CiReplayBase$TestMain test (I)V 1 <appendix> argL0 ;
 206 // // resolve invokedynamic at bci 1 of TestMain.test, then read field "argL0" from appendix
 207 // @bci compiler/ciReplay/CiReplayBase$TestMain main ([Ljava/lang/String;)V 0 <appendix> form vmentry <vmtarget> ;
 208 // // resolve invokedynamic at bci 0 of TestMain.main, then read field "form.vmentry.method.vmtarget" from appendix
 209 // @cpi compiler/ciReplay/CiReplayBase$TestMain 56 form vmentry <vmtarget> ;
 210 // // resolve MethodHandle at cpi 56 of TestMain, then read field "vmentry.method.vmtarget" from resolved MethodHandle
 211 class RecordLocation {
 212 private:
 213   char* end;
 214 
 215   ATTRIBUTE_PRINTF(3, 4)
 216   void push(ciEnv* ci, const char* fmt, ...) {
 217     va_list args;
 218     va_start(args, fmt);
 219     push_va(ci, fmt, args);
 220     va_end(args);
 221   }
 222 
 223 public:
 224   ATTRIBUTE_PRINTF(3, 0)
 225   void push_va(ciEnv* ci, const char* fmt, va_list args) {
 226     char *e = ci->_dyno_name + strlen(ci->_dyno_name);
 227     char *m = ci->_dyno_name + ARRAY_SIZE(ci->_dyno_name) - 1;
 228     (void) os::vsnprintf(e, m - e, fmt, args);
 229     assert(strlen(ci->_dyno_name) < (ARRAY_SIZE(ci->_dyno_name) - 1), "overflow");
 230   }
 231 
 232   // append a new component
 233   ATTRIBUTE_PRINTF(3, 4)
 234   RecordLocation(ciEnv* ci, const char* fmt, ...) {
 235     end = ci->_dyno_name + strlen(ci->_dyno_name);
 236     va_list args;
 237     va_start(args, fmt);
 238     push(ci, " ");
 239     push_va(ci, fmt, args);
 240     va_end(args);
 241   }
 242 
 243   // reset to previous state
 244   ~RecordLocation() {
 245     *end = '\0';
 246   }
 247 };
 248 
 249 ciEnv::ciEnv(Arena* arena) : _ciEnv_arena(mtCompiler, Arena::Tag::tag_cienv) {
 250   ASSERT_IN_VM;
 251 
 252   // Set up ciEnv::current immediately, for the sake of ciObjectFactory, etc.
 253   CompilerThread* current_thread = CompilerThread::current();
 254   assert(current_thread->env() == nullptr, "must be");
 255   current_thread->set_env(this);
 256   assert(ciEnv::current() == this, "sanity");
 257 
 258   _oop_recorder = nullptr;
 259   _debug_info = nullptr;
 260   _dependencies = nullptr;
 261   _inc_decompile_count_on_failure = true;
 262   _compilable = MethodCompilable_never;
 263   _break_at_compile = false;
 264   _compiler_data = nullptr;
 265 #ifndef PRODUCT
 266   assert(firstEnv, "must be first");
 267   firstEnv = false;
 268 #endif /* !PRODUCT */
 269 
 270   _num_inlined_bytecodes = 0;
 271   _task = nullptr;
 272   _log = nullptr;
 273 
 274   // Temporary buffer for creating symbols and such.
 275   _name_buffer = nullptr;
 276   _name_buffer_len = 0;
 277 
 278   _arena   = arena;
 279   _factory = new (_arena) ciObjectFactory(_arena, 128);
 280 
 281   // Preload commonly referenced system ciObjects.
 282 
 283   // During VM initialization, these instances have not yet been created.
 284   // Assertions ensure that these instances are not accessed before
 285   // their initialization.
 286 
 287   assert(Universe::is_fully_initialized(), "must be");
 288 
 289   _NullPointerException_instance = nullptr;
 290   _ArithmeticException_instance = nullptr;
 291   _ArrayIndexOutOfBoundsException_instance = nullptr;
 292   _ArrayStoreException_instance = nullptr;
 293   _ClassCastException_instance = nullptr;
 294   _the_null_string = nullptr;
 295   _the_min_jint_string = nullptr;
 296 
 297   _jvmti_redefinition_count = 0;
 298   _jvmti_can_hotswap_or_post_breakpoint = false;
 299   _jvmti_can_access_local_variables = false;
 300   _jvmti_can_post_on_exceptions = false;
 301   _jvmti_can_pop_frame = false;
 302 
 303   _dyno_klasses = nullptr;
 304   _dyno_locs = nullptr;
 305 }
 306 
 307 ciEnv::~ciEnv() {
 308   GUARDED_VM_ENTRY(
 309       CompilerThread* current_thread = CompilerThread::current();
 310       _factory->remove_symbols();
 311       // Need safepoint to clear the env on the thread.  RedefineClasses might
 312       // be reading it.
 313       current_thread->set_env(nullptr);
 314   )
 315 }
 316 
 317 // ------------------------------------------------------------------
 318 // Cache Jvmti state
 319 bool ciEnv::cache_jvmti_state() {
 320   VM_ENTRY_MARK;
 321   // Get Jvmti capabilities under lock to get consistent values.
 322   MutexLocker mu(JvmtiThreadState_lock);
 323   _jvmti_redefinition_count             = JvmtiExport::redefinition_count();
 324   _jvmti_can_hotswap_or_post_breakpoint = JvmtiExport::can_hotswap_or_post_breakpoint();
 325   _jvmti_can_access_local_variables     = JvmtiExport::can_access_local_variables();
 326   _jvmti_can_post_on_exceptions         = JvmtiExport::can_post_on_exceptions();
 327   _jvmti_can_pop_frame                  = JvmtiExport::can_pop_frame();
 328   _jvmti_can_get_owned_monitor_info     = JvmtiExport::can_get_owned_monitor_info();
 329   _jvmti_can_walk_any_space             = JvmtiExport::can_walk_any_space();
 330   return _task != nullptr && _task->method()->is_old();
 331 }
 332 
 333 bool ciEnv::jvmti_state_changed() const {
 334   // Some classes were redefined
 335   if (_jvmti_redefinition_count != JvmtiExport::redefinition_count()) {
 336     return true;
 337   }
 338 
 339   if (!_jvmti_can_access_local_variables &&
 340       JvmtiExport::can_access_local_variables()) {
 341     return true;
 342   }
 343   if (!_jvmti_can_hotswap_or_post_breakpoint &&
 344       JvmtiExport::can_hotswap_or_post_breakpoint()) {
 345     return true;
 346   }
 347   if (!_jvmti_can_post_on_exceptions &&
 348       JvmtiExport::can_post_on_exceptions()) {
 349     return true;
 350   }
 351   if (!_jvmti_can_pop_frame &&
 352       JvmtiExport::can_pop_frame()) {
 353     return true;
 354   }
 355   if (!_jvmti_can_get_owned_monitor_info &&
 356       JvmtiExport::can_get_owned_monitor_info()) {
 357     return true;
 358   }
 359   if (!_jvmti_can_walk_any_space &&
 360       JvmtiExport::can_walk_any_space()) {
 361     return true;
 362   }
 363 
 364   return false;
 365 }
 366 
 367 // ------------------------------------------------------------------
 368 // Cache DTrace flags
 369 void ciEnv::cache_dtrace_flags() {
 370   // Need lock?
 371   _dtrace_method_probes = DTraceMethodProbes;
 372   _dtrace_alloc_probes  = DTraceAllocProbes;
 373 }
 374 
 375 ciInstanceKlass* ciEnv::get_box_klass_for_primitive_type(BasicType type) {
 376   switch (type) {
 377     case T_BOOLEAN: return Boolean_klass();
 378     case T_BYTE   : return Byte_klass();
 379     case T_CHAR   : return Character_klass();
 380     case T_SHORT  : return Short_klass();
 381     case T_INT    : return Integer_klass();
 382     case T_LONG   : return Long_klass();
 383     case T_FLOAT  : return Float_klass();
 384     case T_DOUBLE : return Double_klass();
 385 
 386     default:
 387       assert(false, "not a primitive: %s", type2name(type));
 388       return nullptr;
 389   }
 390 }
 391 
 392 ciInstance* ciEnv::the_null_string() {
 393   if (_the_null_string == nullptr) {
 394     VM_ENTRY_MARK;
 395     _the_null_string = get_object(Universe::the_null_string())->as_instance();
 396   }
 397   return _the_null_string;
 398 }
 399 
 400 ciInstance* ciEnv::the_min_jint_string() {
 401   if (_the_min_jint_string == nullptr) {
 402     VM_ENTRY_MARK;
 403     _the_min_jint_string = get_object(Universe::the_min_jint_string())->as_instance();
 404   }
 405   return _the_min_jint_string;
 406 }
 407 
 408 // ------------------------------------------------------------------
 409 // ciEnv::get_method_from_handle
 410 ciMethod* ciEnv::get_method_from_handle(Method* method) {
 411   VM_ENTRY_MARK;
 412   return get_metadata(method)->as_method();
 413 }
 414 
 415 // ------------------------------------------------------------------
 416 // ciEnv::check_klass_accessiblity
 417 //
 418 // Note: the logic of this method should mirror the logic of
 419 // ConstantPool::verify_constant_pool_resolve.
 420 bool ciEnv::check_klass_accessibility(ciKlass* accessing_klass,
 421                                       Klass* resolved_klass) {
 422   if (accessing_klass == nullptr || !accessing_klass->is_loaded()) {
 423     return true;
 424   }
 425   if (accessing_klass->is_obj_array_klass()) {
 426     accessing_klass = accessing_klass->as_obj_array_klass()->base_element_klass();
 427   }
 428   if (!accessing_klass->is_instance_klass()) {
 429     return true;
 430   }
 431 
 432   if (resolved_klass->is_objArray_klass()) {
 433     // Find the element klass, if this is an array.
 434     resolved_klass = ObjArrayKlass::cast(resolved_klass)->bottom_klass();
 435   }
 436   if (resolved_klass->is_instance_klass()) {
 437     return (Reflection::verify_class_access(accessing_klass->get_Klass(),
 438                                             InstanceKlass::cast(resolved_klass),
 439                                             true) == Reflection::ACCESS_OK);
 440   }
 441   return true;
 442 }
 443 
 444 // ------------------------------------------------------------------
 445 // ciEnv::get_klass_by_name_impl
 446 ciKlass* ciEnv::get_klass_by_name_impl(ciKlass* accessing_klass,
 447                                        const constantPoolHandle& cpool,
 448                                        ciSymbol* name,
 449                                        bool require_local) {
 450   ASSERT_IN_VM;
 451   Thread* current = Thread::current();
 452 
 453   // Now we need to check the SystemDictionary
 454   Symbol* sym = name->get_symbol();
 455   if (Signature::has_envelope(sym)) {
 456     // This is a name from a signature.  Strip off the trimmings.
 457     // Call recursive to keep scope of strippedsym.
 458     TempNewSymbol strippedsym = Signature::strip_envelope(sym);
 459     ciSymbol* strippedname = get_symbol(strippedsym);
 460     return get_klass_by_name_impl(accessing_klass, cpool, strippedname, require_local);
 461   }
 462 
 463   // Check for prior unloaded klass.  The SystemDictionary's answers
 464   // can vary over time but the compiler needs consistency.
 465   ciKlass* unloaded_klass = check_get_unloaded_klass(accessing_klass, name);
 466   if (unloaded_klass != nullptr) {
 467     if (require_local)  return nullptr;
 468     return unloaded_klass;
 469   }
 470 
 471   Handle loader;
 472   if (accessing_klass != nullptr) {
 473     loader = Handle(current, accessing_klass->loader());
 474   }
 475 
 476   Klass* found_klass = require_local ?
 477                          SystemDictionary::find_instance_or_array_klass(current, sym, loader) :
 478                          SystemDictionary::find_constrained_instance_or_array_klass(current, sym, loader);
 479 
 480   // If we fail to find an array klass, look again for its element type.
 481   // The element type may be available either locally or via constraints.
 482   // In either case, if we can find the element type in the system dictionary,
 483   // we must build an array type around it.  The CI requires array klasses
 484   // to be loaded if their element klasses are loaded, except when memory
 485   // is exhausted.
 486   if (Signature::is_array(sym) &&
 487       (sym->char_at(1) == JVM_SIGNATURE_ARRAY || sym->char_at(1) == JVM_SIGNATURE_CLASS)) {
 488     // We have an unloaded array.
 489     // Build it on the fly if the element class exists.
 490     SignatureStream ss(sym, false);
 491     ss.skip_array_prefix(1);
 492     // Get element ciKlass recursively.
 493     ciKlass* elem_klass =
 494       get_klass_by_name_impl(accessing_klass,
 495                              cpool,
 496                              get_symbol(ss.as_symbol()),
 497                              require_local);
 498     if (elem_klass != nullptr && elem_klass->is_loaded()) {
 499       // Now make an array for it
 500       return ciObjArrayKlass::make_impl(elem_klass);
 501     }
 502   }
 503 
 504   if (found_klass == nullptr && !cpool.is_null() && cpool->has_preresolution()) {
 505     // Look inside the constant pool for pre-resolved class entries.
 506     for (int i = cpool->length() - 1; i >= 1; i--) {
 507       if (cpool->tag_at(i).is_klass()) {
 508         Klass* kls = cpool->resolved_klass_at(i);
 509         if (kls->name() == sym) {
 510           found_klass = kls;
 511           break;
 512         }
 513       }
 514     }
 515   }
 516 
 517   if (found_klass != nullptr) {
 518     // Found it.  Build a CI handle.
 519     return get_klass(found_klass);
 520   }
 521 
 522   if (require_local)  return nullptr;
 523 
 524   // Not yet loaded into the VM, or not governed by loader constraints.
 525   // Make a CI representative for it.
 526   return get_unloaded_klass(accessing_klass, name);
 527 }
 528 
 529 // ------------------------------------------------------------------
 530 // ciEnv::get_klass_by_name
 531 ciKlass* ciEnv::get_klass_by_name(ciKlass* accessing_klass,
 532                                   ciSymbol* klass_name,
 533                                   bool require_local) {
 534   GUARDED_VM_ENTRY(return get_klass_by_name_impl(accessing_klass,
 535                                                  constantPoolHandle(),
 536                                                  klass_name,
 537                                                  require_local);)
 538 }
 539 
 540 // ------------------------------------------------------------------
 541 // ciEnv::get_klass_by_index_impl
 542 //
 543 // Implementation of get_klass_by_index.
 544 ciKlass* ciEnv::get_klass_by_index_impl(const constantPoolHandle& cpool,
 545                                         int index,
 546                                         bool& is_accessible,
 547                                         ciInstanceKlass* accessor) {
 548   Klass* klass = nullptr;
 549   Symbol* klass_name = nullptr;
 550 
 551   if (cpool->tag_at(index).is_symbol()) {
 552     klass_name = cpool->symbol_at(index);
 553   } else {
 554     // Check if it's resolved if it's not a symbol constant pool entry.
 555     klass = ConstantPool::klass_at_if_loaded(cpool, index);
 556     // Try to look it up by name.
 557     if (klass == nullptr) {
 558       klass_name = cpool->klass_name_at(index);
 559     }
 560   }
 561 
 562   if (klass == nullptr) {
 563     // Not found in constant pool.  Use the name to do the lookup.
 564     ciKlass* k = get_klass_by_name_impl(accessor,
 565                                         cpool,
 566                                         get_symbol(klass_name),
 567                                         false);
 568     // Calculate accessibility the hard way.
 569     if (!k->is_loaded()) {
 570       is_accessible = false;
 571     } else if (k->loader() != accessor->loader() &&
 572                get_klass_by_name_impl(accessor, cpool, k->name(), true) == nullptr) {
 573       // Loaded only remotely.  Not linked yet.
 574       is_accessible = false;
 575     } else {
 576       // Linked locally, and we must also check public/private, etc.
 577       is_accessible = check_klass_accessibility(accessor, k->get_Klass());
 578     }
 579     return k;
 580   }
 581 
 582   // Check for prior unloaded klass.  The SystemDictionary's answers
 583   // can vary over time but the compiler needs consistency.
 584   ciSymbol* name = get_symbol(klass->name());
 585   ciKlass* unloaded_klass = check_get_unloaded_klass(accessor, name);
 586   if (unloaded_klass != nullptr) {
 587     is_accessible = false;
 588     return unloaded_klass;
 589   }
 590 
 591   // It is known to be accessible, since it was found in the constant pool.
 592   ciKlass* ciKlass = get_klass(klass);
 593   is_accessible = true;
 594   if (ReplayCompiles && ciKlass == _unloaded_ciinstance_klass) {
 595     // Klass was unresolved at replay dump time and therefore not accessible.
 596     is_accessible = false;
 597   }
 598   return ciKlass;
 599 }
 600 
 601 // ------------------------------------------------------------------
 602 // ciEnv::get_klass_by_index
 603 //
 604 // Get a klass from the constant pool.
 605 ciKlass* ciEnv::get_klass_by_index(const constantPoolHandle& cpool,
 606                                    int index,
 607                                    bool& is_accessible,
 608                                    ciInstanceKlass* accessor) {
 609   GUARDED_VM_ENTRY(return get_klass_by_index_impl(cpool, index, is_accessible, accessor);)
 610 }
 611 
 612 // ------------------------------------------------------------------
 613 // ciEnv::unbox_primitive_value
 614 //
 615 // Unbox a primitive and return it as a ciConstant.
 616 ciConstant ciEnv::unbox_primitive_value(ciObject* cibox, BasicType expected_bt) {
 617   jvalue value;
 618   BasicType bt = java_lang_boxing_object::get_value(cibox->get_oop(), &value);
 619   if (bt != expected_bt && expected_bt != T_ILLEGAL) {
 620     assert(false, "type mismatch: %s vs %s", type2name(expected_bt), cibox->klass()->name()->as_klass_external_name());
 621     return ciConstant();
 622   }
 623   switch (bt) {
 624     case T_BOOLEAN: return ciConstant(bt, value.z);
 625     case T_BYTE:    return ciConstant(bt, value.b);
 626     case T_SHORT:   return ciConstant(bt, value.s);
 627     case T_CHAR:    return ciConstant(bt, value.c);
 628     case T_INT:     return ciConstant(bt, value.i);
 629     case T_LONG:    return ciConstant(value.j);
 630     case T_FLOAT:   return ciConstant(value.f);
 631     case T_DOUBLE:  return ciConstant(value.d);
 632 
 633     default:
 634       assert(false, "not a primitive type: %s", type2name(bt));
 635       return ciConstant();
 636   }
 637 }
 638 
 639 // ------------------------------------------------------------------
 640 // ciEnv::get_resolved_constant
 641 //
 642 ciConstant ciEnv::get_resolved_constant(const constantPoolHandle& cpool, int obj_index) {
 643   assert(obj_index >= 0, "");
 644   oop obj = cpool->resolved_reference_at(obj_index);
 645   if (obj == nullptr) {
 646     // Unresolved constant. It is resolved when the corresponding slot contains a non-null reference.
 647     // Null constant is represented as a sentinel (non-null) value.
 648     return ciConstant();
 649   } else if (obj == Universe::the_null_sentinel()) {
 650     return ciConstant(T_OBJECT, get_object(nullptr));
 651   } else {
 652     ciObject* ciobj = get_object(obj);
 653     if (ciobj->is_array()) {
 654       return ciConstant(T_ARRAY, ciobj);
 655     } else {
 656       int cp_index = cpool->object_to_cp_index(obj_index);
 657       BasicType bt = cpool->basic_type_for_constant_at(cp_index);
 658       if (is_java_primitive(bt)) {
 659         assert(cpool->tag_at(cp_index).is_dynamic_constant(), "sanity");
 660         return unbox_primitive_value(ciobj, bt);
 661       } else {
 662         assert(ciobj->is_instance(), "should be an instance");
 663         return ciConstant(T_OBJECT, ciobj);
 664       }
 665     }
 666   }
 667 }
 668 
 669 // ------------------------------------------------------------------
 670 // ciEnv::get_constant_by_index_impl
 671 //
 672 // Implementation of get_constant_by_index().
 673 ciConstant ciEnv::get_constant_by_index_impl(const constantPoolHandle& cpool,
 674                                              int index, int obj_index,
 675                                              ciInstanceKlass* accessor) {
 676   if (obj_index >= 0) {
 677     ciConstant con = get_resolved_constant(cpool, obj_index);
 678     if (con.should_be_constant()) {
 679       return con;
 680     }
 681   }
 682   constantTag tag = cpool->tag_at(index);
 683   if (tag.is_int()) {
 684     return ciConstant(T_INT, (jint)cpool->int_at(index));
 685   } else if (tag.is_long()) {
 686     return ciConstant((jlong)cpool->long_at(index));
 687   } else if (tag.is_float()) {
 688     return ciConstant((jfloat)cpool->float_at(index));
 689   } else if (tag.is_double()) {
 690     return ciConstant((jdouble)cpool->double_at(index));
 691   } else if (tag.is_string()) {
 692     EXCEPTION_CONTEXT;
 693     assert(obj_index >= 0, "should have an object index");
 694     oop string = cpool->string_at(index, obj_index, THREAD);
 695     if (HAS_PENDING_EXCEPTION) {
 696       CLEAR_PENDING_EXCEPTION;
 697       record_out_of_memory_failure();
 698       return ciConstant();
 699     }
 700     ciInstance* constant = get_object(string)->as_instance();
 701     return ciConstant(T_OBJECT, constant);
 702   } else if (tag.is_unresolved_klass_in_error()) {
 703     return ciConstant(T_OBJECT, get_unloaded_klass_mirror(nullptr));
 704   } else if (tag.is_klass() || tag.is_unresolved_klass()) {
 705     bool will_link;
 706     ciKlass* klass = get_klass_by_index_impl(cpool, index, will_link, accessor);
 707     ciInstance* mirror = (will_link ? klass->java_mirror() : get_unloaded_klass_mirror(klass));
 708     return ciConstant(T_OBJECT, mirror);
 709   } else if (tag.is_method_type() || tag.is_method_type_in_error()) {
 710     // must execute Java code to link this CP entry into cache[i].f1
 711     assert(obj_index >= 0, "should have an object index");
 712     ciSymbol* signature = get_symbol(cpool->method_type_signature_at(index));
 713     ciObject* ciobj = get_unloaded_method_type_constant(signature);
 714     return ciConstant(T_OBJECT, ciobj);
 715   } else if (tag.is_method_handle() || tag.is_method_handle_in_error()) {
 716     // must execute Java code to link this CP entry into cache[i].f1
 717     assert(obj_index >= 0, "should have an object index");
 718     bool ignore_will_link;
 719     int ref_kind        = cpool->method_handle_ref_kind_at(index);
 720     int callee_index    = cpool->method_handle_klass_index_at(index);
 721     ciKlass* callee     = get_klass_by_index_impl(cpool, callee_index, ignore_will_link, accessor);
 722     ciSymbol* name      = get_symbol(cpool->method_handle_name_ref_at(index));
 723     ciSymbol* signature = get_symbol(cpool->method_handle_signature_ref_at(index));
 724     ciObject* ciobj     = get_unloaded_method_handle_constant(callee, name, signature, ref_kind);
 725     return ciConstant(T_OBJECT, ciobj);
 726   } else if (tag.is_dynamic_constant() || tag.is_dynamic_constant_in_error()) {
 727     assert(obj_index >= 0, "should have an object index");
 728     return ciConstant(T_OBJECT, unloaded_ciinstance()); // unresolved dynamic constant
 729   } else {
 730     assert(false, "unknown tag: %d (%s)", tag.value(), tag.internal_name());
 731     return ciConstant();
 732   }
 733 }
 734 
 735 // ------------------------------------------------------------------
 736 // ciEnv::get_constant_by_index
 737 //
 738 // Pull a constant out of the constant pool.  How appropriate.
 739 //
 740 // Implementation note: this query is currently in no way cached.
 741 ciConstant ciEnv::get_constant_by_index(const constantPoolHandle& cpool,
 742                                         int pool_index, int cache_index,
 743                                         ciInstanceKlass* accessor) {
 744   GUARDED_VM_ENTRY(return get_constant_by_index_impl(cpool, pool_index, cache_index, accessor);)
 745 }
 746 
 747 // ------------------------------------------------------------------
 748 // ciEnv::get_field_by_index_impl
 749 //
 750 // Implementation of get_field_by_index.
 751 //
 752 // Implementation note: the results of field lookups are cached
 753 // in the accessor klass.
 754 ciField* ciEnv::get_field_by_index_impl(ciInstanceKlass* accessor,
 755                                         int index, Bytecodes::Code bc) {
 756   ciConstantPoolCache* cache = accessor->field_cache();
 757   if (cache == nullptr) {
 758     ciField* field = new (arena()) ciField(accessor, index, bc);
 759     return field;
 760   } else {
 761     ciField* field = (ciField*)cache->get(index);
 762     if (field == nullptr) {
 763       field = new (arena()) ciField(accessor, index, bc);
 764       cache->insert(index, field);
 765     }
 766     return field;
 767   }
 768 }
 769 
 770 // ------------------------------------------------------------------
 771 // ciEnv::get_field_by_index
 772 //
 773 // Get a field by index from a klass's constant pool.
 774 ciField* ciEnv::get_field_by_index(ciInstanceKlass* accessor,
 775                                    int index, Bytecodes::Code bc) {
 776   GUARDED_VM_ENTRY(return get_field_by_index_impl(accessor, index, bc);)
 777 }
 778 
 779 // ------------------------------------------------------------------
 780 // ciEnv::lookup_method
 781 //
 782 // Perform an appropriate method lookup based on accessor, holder,
 783 // name, signature, and bytecode.
 784 Method* ciEnv::lookup_method(ciInstanceKlass* accessor,
 785                              ciKlass*         holder,
 786                              Symbol*          name,
 787                              Symbol*          sig,
 788                              Bytecodes::Code  bc,
 789                              constantTag      tag) {
 790   InstanceKlass* accessor_klass = accessor->get_instanceKlass();
 791   Klass* holder_klass = holder->get_Klass();
 792 
 793   // Accessibility checks are performed in ciEnv::get_method_by_index_impl.
 794   assert(check_klass_accessibility(accessor, holder_klass), "holder not accessible");
 795 
 796   LinkInfo link_info(holder_klass, name, sig, accessor_klass,
 797                      LinkInfo::AccessCheck::required,
 798                      LinkInfo::LoaderConstraintCheck::required,
 799                      tag);
 800   switch (bc) {
 801     case Bytecodes::_invokestatic:
 802       return LinkResolver::resolve_static_call_or_null(link_info);
 803     case Bytecodes::_invokespecial:
 804       return LinkResolver::resolve_special_call_or_null(link_info);
 805     case Bytecodes::_invokeinterface:
 806       return LinkResolver::linktime_resolve_interface_method_or_null(link_info);
 807     case Bytecodes::_invokevirtual:
 808       return LinkResolver::linktime_resolve_virtual_method_or_null(link_info);
 809     default:
 810       fatal("Unhandled bytecode: %s", Bytecodes::name(bc));
 811       return nullptr; // silence compiler warnings
 812   }
 813 }
 814 
 815 
 816 // ------------------------------------------------------------------
 817 // ciEnv::get_method_by_index_impl
 818 ciMethod* ciEnv::get_method_by_index_impl(const constantPoolHandle& cpool,
 819                                           int index, Bytecodes::Code bc,
 820                                           ciInstanceKlass* accessor) {
 821   assert(cpool.not_null(), "need constant pool");
 822   assert(accessor != nullptr, "need origin of access");
 823   if (bc == Bytecodes::_invokedynamic) {
 824     // FIXME: code generation could allow for null (unlinked) call site
 825     // The call site could be made patchable as follows:
 826     // Load the appendix argument from the constant pool.
 827     // Test the appendix argument and jump to a known deopt routine if it is null.
 828     // Jump through a patchable call site, which is initially a deopt routine.
 829     // Patch the call site to the nmethod entry point of the static compiled lambda form.
 830     // As with other two-component call sites, both values must be independently verified.
 831     assert(index < cpool->cache()->resolved_indy_entries_length(), "impossible");
 832     ResolvedIndyEntry* indy_info = cpool->resolved_indy_entry_at(index);
 833     Method* adapter = indy_info->method();
 834 #if INCLUDE_CDS
 835     if (is_precompile() && !AOTConstantPoolResolver::is_resolution_deterministic(cpool(), indy_info->constant_pool_index())) {
 836       // This is an indy callsite that was resolved as a side effect of VM bootstrap, but
 837       // it cannot be cached in the resolved state, so AOT code should not reference it.
 838       adapter = nullptr;
 839     }
 840 #endif
 841     // Resolved if the adapter is non null.
 842     if (adapter != nullptr) {
 843       return get_method(adapter);
 844     }
 845 
 846     // Fake a method that is equivalent to a declared method.
 847     ciInstanceKlass* holder    = get_instance_klass(vmClasses::MethodHandle_klass());
 848     ciSymbol*        name      = ciSymbols::invokeBasic_name();
 849     ciSymbol*        signature = get_symbol(cpool->signature_ref_at(index, bc));
 850     return get_unloaded_method(holder, name, signature, accessor);
 851   } else {
 852     const int holder_index = cpool->klass_ref_index_at(index, bc);
 853     bool holder_is_accessible;
 854     ciKlass* holder = get_klass_by_index_impl(cpool, holder_index, holder_is_accessible, accessor);
 855 
 856     // Get the method's name and signature.
 857     Symbol* name_sym = cpool->name_ref_at(index, bc);
 858     Symbol* sig_sym  = cpool->signature_ref_at(index, bc);
 859 
 860     if (cpool->has_preresolution()
 861         || ((holder == ciEnv::MethodHandle_klass() || holder == ciEnv::VarHandle_klass()) &&
 862             MethodHandles::is_signature_polymorphic_name(holder->get_Klass(), name_sym))) {
 863       // Short-circuit lookups for JSR 292-related call sites.
 864       // That is, do not rely only on name-based lookups, because they may fail
 865       // if the names are not resolvable in the boot class loader (7056328).
 866       switch (bc) {
 867       case Bytecodes::_invokevirtual:
 868       case Bytecodes::_invokeinterface:
 869       case Bytecodes::_invokespecial:
 870       case Bytecodes::_invokestatic:
 871         {
 872           Method* m = ConstantPool::method_at_if_loaded(cpool, index);
 873           if (m != nullptr) {
 874             return get_method(m);
 875           }
 876         }
 877         break;
 878       default:
 879         break;
 880       }
 881     }
 882 
 883     if (holder_is_accessible) {  // Our declared holder is loaded.
 884       constantTag tag = cpool->tag_ref_at(index, bc);
 885       assert(accessor->get_instanceKlass() == cpool->pool_holder(), "not the pool holder?");
 886       Method* m = lookup_method(accessor, holder, name_sym, sig_sym, bc, tag);
 887       if (m != nullptr) {
 888         ciInstanceKlass* cik = get_instance_klass(m->method_holder());
 889         if ((bc == Bytecodes::_invokestatic && cik->is_not_initialized()) || !cik->is_loaded()) {
 890           m = nullptr;
 891         }
 892       }
 893       if (m != nullptr && ReplayCompiles && !ciReplay::is_loaded(m)) {
 894         m = nullptr;
 895       }
 896       if (m != nullptr) {
 897         // We found the method.
 898         return get_method(m);
 899       }
 900     }
 901 
 902     // Either the declared holder was not loaded, or the method could
 903     // not be found.  Create a dummy ciMethod to represent the failed
 904     // lookup.
 905     ciSymbol* name      = get_symbol(name_sym);
 906     ciSymbol* signature = get_symbol(sig_sym);
 907     return get_unloaded_method(holder, name, signature, accessor);
 908   }
 909 }
 910 
 911 
 912 // ------------------------------------------------------------------
 913 // ciEnv::get_instance_klass_for_declared_method_holder
 914 ciInstanceKlass* ciEnv::get_instance_klass_for_declared_method_holder(ciKlass* method_holder) {
 915   // For the case of <array>.clone(), the method holder can be a ciArrayKlass
 916   // instead of a ciInstanceKlass.  For that case simply pretend that the
 917   // declared holder is Object.clone since that's where the call will bottom out.
 918   // A more correct fix would trickle out through many interfaces in CI,
 919   // requiring ciInstanceKlass* to become ciKlass* and many more places would
 920   // require checks to make sure the expected type was found.  Given that this
 921   // only occurs for clone() the more extensive fix seems like overkill so
 922   // instead we simply smear the array type into Object.
 923   guarantee(method_holder != nullptr, "no method holder");
 924   if (method_holder->is_instance_klass()) {
 925     return method_holder->as_instance_klass();
 926   } else if (method_holder->is_array_klass()) {
 927     return current()->Object_klass();
 928   } else {
 929     ShouldNotReachHere();
 930   }
 931   return nullptr;
 932 }
 933 
 934 
 935 // ------------------------------------------------------------------
 936 // ciEnv::get_method_by_index
 937 ciMethod* ciEnv::get_method_by_index(const constantPoolHandle& cpool,
 938                                      int index, Bytecodes::Code bc,
 939                                      ciInstanceKlass* accessor) {
 940   GUARDED_VM_ENTRY(return get_method_by_index_impl(cpool, index, bc, accessor);)
 941 }
 942 
 943 
 944 // ------------------------------------------------------------------
 945 // ciEnv::name_buffer
 946 char *ciEnv::name_buffer(int req_len) {
 947   if (_name_buffer_len < req_len) {
 948     if (_name_buffer == nullptr) {
 949       _name_buffer = (char*)arena()->Amalloc(sizeof(char)*req_len);
 950       _name_buffer_len = req_len;
 951     } else {
 952       _name_buffer =
 953         (char*)arena()->Arealloc(_name_buffer, _name_buffer_len, req_len);
 954       _name_buffer_len = req_len;
 955     }
 956   }
 957   return _name_buffer;
 958 }
 959 
 960 // ------------------------------------------------------------------
 961 // ciEnv::is_in_vm
 962 bool ciEnv::is_in_vm() {
 963   return JavaThread::current()->thread_state() == _thread_in_vm;
 964 }
 965 
 966 // ------------------------------------------------------------------
 967 // ciEnv::validate_compile_task_dependencies
 968 //
 969 // Check for changes during compilation (e.g. class loads, evolution,
 970 // breakpoints, call site invalidation).
 971 void ciEnv::validate_compile_task_dependencies(ciMethod* target) {
 972   assert(!failing(), "should not call this when failing");
 973 
 974   Dependencies::DepType result = dependencies()->validate_dependencies(_task);
 975   if (result != Dependencies::end_marker) {
 976     if (result == Dependencies::call_site_target_value) {
 977       _inc_decompile_count_on_failure = false;
 978       record_failure("call site target change");
 979     } else if (Dependencies::is_klass_type(result)) {
 980       record_failure("concurrent class loading");
 981     } else {
 982       record_failure("invalid non-klass dependency");
 983     }
 984   }
 985 }
 986 
 987 // is_loading_aot_code = true implies loading compiled code from AOT code cache
 988 bool ciEnv::is_compilation_valid(JavaThread* thread, ciMethod* target, bool install_code, bool is_loading_aot_code, bool preload) {
 989   methodHandle method(thread, target->get_Method());
 990 
 991   // We require method counters to store some method state (max compilation levels) required by the compilation policy.
 992   if (!preload && method->get_method_counters(thread) == nullptr) {
 993     record_failure("can't create method counters");
 994     return false;
 995   }
 996 
 997   // Change in Jvmti state may invalidate compilation.
 998   if (!failing() && jvmti_state_changed()) {
 999     record_failure("Jvmti state change invalidated dependencies");
1000   }
1001 
1002   // Change in DTrace flags may invalidate compilation.
1003   if (!failing() &&
1004       ( (!dtrace_method_probes() && DTraceMethodProbes) ||
1005         (!dtrace_alloc_probes() && DTraceAllocProbes) )) {
1006     record_failure("DTrace flags change invalidated dependencies");
1007   }
1008 
1009   if (!preload && !failing() && target->needs_clinit_barrier() &&
1010       target->holder()->is_in_error_state()) {
1011     record_failure("method holder is in error state");
1012   }
1013 
1014   if (!failing() && !is_loading_aot_code) {
1015     if (log() != nullptr) {
1016       // Log the dependencies which this compilation declares.
1017       dependencies()->log_all_dependencies();
1018     }
1019 
1020     // Encode the dependencies now, so we can check them right away.
1021     dependencies()->encode_content_bytes();
1022   }
1023   // Check for {class loads, evolution, breakpoints, ...} during compilation
1024   if (!failing() && install_code) {
1025     // Check for {class loads, evolution, breakpoints, ...} during compilation
1026     validate_compile_task_dependencies(target);
1027     if (failing() && preload) {
1028       ResourceMark rm;
1029       char *method_name = method->name_and_sig_as_C_string();
1030       log_info(aot, codecache)("preload code for '%s' failed dependency check", method_name);
1031     }
1032   }
1033 
1034   if (failing()) {
1035     // While not a true deoptimization, it is a preemptive decompile.
1036     MethodData* mdo = method()->method_data();
1037     if (mdo != nullptr && _inc_decompile_count_on_failure) {
1038       mdo->inc_decompile_count();
1039     }
1040     return false;
1041   }
1042   return true;
1043 }
1044 
1045 void ciEnv::make_code_usable(JavaThread* thread, ciMethod* target, bool preload, int entry_bci, AOTCodeEntry* aot_code_entry, nmethod* nm) {
1046   methodHandle method(thread, target->get_Method());
1047 
1048   if (entry_bci == InvocationEntryBci) {
1049     if (TieredCompilation) {
1050       // If there is an old version we're done with it
1051       nmethod* old = method->code();
1052       if (TraceMethodReplacement && old != nullptr) {
1053         ResourceMark rm;
1054         char *method_name = method->name_and_sig_as_C_string();
1055         tty->print_cr("Replacing method %s", method_name);
1056       }
1057       if (old != nullptr) {
1058         old->make_not_used();
1059       }
1060     }
1061 
1062     LogTarget(Info, nmethod, install) lt;
1063     if (lt.is_enabled()) {
1064       ResourceMark rm;
1065       char *method_name = method->name_and_sig_as_C_string();
1066       lt.print("Installing method (L%d) %s id=%d aot=%s%s%u",
1067                task()->comp_level(), method_name, compile_id(),
1068                task()->is_aot_load() ? "A" : "", preload ? "P" : "",
1069                (aot_code_entry != nullptr ? aot_code_entry->offset() : 0));
1070     }
1071     // Allow the code to be executed
1072     MutexLocker ml(NMethodState_lock, Mutex::_no_safepoint_check_flag);
1073     if (nm->make_in_use()) {
1074 #ifdef ASSERT
1075       BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
1076       if (bs_nm != nullptr && bs_nm->supports_entry_barrier(nm)) {
1077         if (!bs_nm->is_armed(nm)) {
1078           log_info(init)("nmethod %d %d not armed", nm->compile_id(), nm->comp_level());
1079         }
1080       }
1081 #endif // ASSERT
1082       if (preload) {
1083         nm->set_preloaded(true);
1084         method->set_preload_code(nm);
1085       }
1086       if (!preload || target->holder()->is_linked()) {
1087         method->set_code(method, nm);
1088       }
1089     }
1090   } else {
1091     LogTarget(Info, nmethod, install) lt;
1092     if (lt.is_enabled()) {
1093       assert(aot_code_entry == nullptr && !task()->is_aot_load(), "OSR nmethods are not AOT compiled");
1094       ResourceMark rm;
1095       char *method_name = method->name_and_sig_as_C_string();
1096       lt.print("Installing osr method (L%d) %s @ %d id=%u",
1097                task()->comp_level(), method_name, entry_bci, compile_id());
1098     }
1099     MutexLocker ml(NMethodState_lock, Mutex::_no_safepoint_check_flag);
1100     if (nm->make_in_use()) {
1101       method->method_holder()->add_osr_nmethod(nm);
1102     }
1103   }
1104 }
1105 
1106 nmethod* ciEnv::register_aot_method(JavaThread* thread,
1107                                 ciMethod* target,
1108                                 AbstractCompiler* compiler,
1109                                 nmethod* archived_nm,
1110                                 address reloc_data,
1111                                 GrowableArray<Handle>& oop_list,
1112                                 GrowableArray<Metadata*>& metadata_list,
1113                                 ImmutableOopMapSet* oopmaps,
1114                                 address immutable_data,
1115                                 GrowableArray<Handle>& reloc_imm_oop_list,
1116                                 GrowableArray<Metadata*>& reloc_imm_metadata_list,
1117                                 AOTCodeReader* aot_code_reader)
1118 {
1119   AOTCodeEntry* aot_code_entry = task()->aot_code_entry();
1120   assert(aot_code_entry != nullptr, "must be");
1121   nmethod* nm = nullptr;
1122   {
1123     methodHandle method(thread, target->get_Method());
1124     bool preload = task()->preload(); // Code is preloaded before Java method execution
1125 
1126     // Check if memory should be freed before allocation
1127     CodeCache::gc_on_allocation();
1128 
1129     // To prevent compile queue updates.
1130     MutexLocker locker(thread, task()->compile_queue()->lock());
1131 
1132     // Prevent InstanceKlass::add_to_hierarchy from running
1133     // and invalidating our dependencies until we install this method.
1134     // No safepoints are allowed. Otherwise, class redefinition can occur in between.
1135     MutexLocker ml(Compile_lock);
1136     NoSafepointVerifier nsv;
1137 
1138     // AOTCode entry indicates this shared code was marked invalid while it was loaded.
1139     if (aot_code_entry->not_entrant()) {
1140       return nullptr;
1141     }
1142 
1143     if (!is_compilation_valid(thread, target, true /*install_code*/, true, preload)) {
1144       return nullptr;
1145     }
1146 
1147     nm = nmethod::new_nmethod(archived_nm,
1148                               method,
1149                               compiler,
1150                               compile_id(),
1151                               reloc_data,
1152                               oop_list,
1153                               metadata_list,
1154                               oopmaps,
1155                               immutable_data,
1156                               reloc_imm_oop_list,
1157                               reloc_imm_metadata_list,
1158                               aot_code_reader);
1159 
1160     if (nm != nullptr) {
1161       aot_code_entry->set_loaded();
1162       make_code_usable(thread, target, preload, InvocationEntryBci, aot_code_entry, nm);
1163     }
1164   }
1165 
1166   NoSafepointVerifier nsv;
1167   if (nm != nullptr) {
1168     // Compilation succeeded, post what we know about it
1169     nm->post_compiled_method(task());
1170     task()->set_num_inlined_bytecodes(num_inlined_bytecodes());
1171   } else {
1172     // The CodeCache is full.
1173     record_failure("code cache is full");
1174   }
1175   return nm;
1176   // safepoints are allowed again
1177 }
1178 
1179 // ------------------------------------------------------------------
1180 // ciEnv::register_method
1181 void ciEnv::register_method(ciMethod* target,
1182                             int entry_bci,
1183                             CodeOffsets* offsets,
1184                             int orig_pc_offset,
1185                             CodeBuffer* code_buffer,
1186                             int frame_words,
1187                             OopMapSet* oop_map_set,
1188                             ExceptionHandlerTable* handler_table,
1189                             ImplicitExceptionTable* inc_table,
1190                             AbstractCompiler* compiler,
1191                             bool has_clinit_barriers,
1192                             bool for_preload,
1193                             bool has_unsafe_access,
1194                             bool has_wide_vectors,
1195                             bool has_monitors,
1196                             bool has_scoped_access,
1197                             int immediate_oops_patched,
1198                             bool install_code) {
1199   VM_ENTRY_MARK;
1200   nmethod* nm = nullptr;
1201   {
1202     methodHandle method(THREAD, target->get_Method());
1203 
1204     // Check if memory should be freed before allocation
1205     CodeCache::gc_on_allocation();
1206 
1207     // To prevent compile queue updates.
1208     MutexLocker locker(THREAD, task()->compile_queue()->lock());
1209 
1210     // Prevent InstanceKlass::add_to_hierarchy from running
1211     // and invalidating our dependencies until we install this method.
1212     // No safepoints are allowed. Otherwise, class redefinition can occur in between.
1213     MutexLocker ml(Compile_lock);
1214     NoSafepointVerifier nsv;
1215 
1216     if (!is_compilation_valid(THREAD, target, install_code, /*aot_code_entry*/ false, /*preload*/ false)) {
1217       code_buffer->free_blob();
1218       return;
1219     }
1220 
1221     assert(offsets->value(CodeOffsets::Deopt) != -1, "must have deopt entry");
1222 
1223     assert(compiler->type() == compiler_c2 ||
1224            offsets->value(CodeOffsets::Exceptions) != -1, "must have exception entry");
1225 
1226     if (install_code) {
1227       nm =  nmethod::new_nmethod(method,
1228                                  compile_id(),
1229                                  entry_bci,
1230                                  offsets,
1231                                  orig_pc_offset,
1232                                  debug_info(), dependencies(), code_buffer,
1233                                  frame_words, oop_map_set,
1234                                  handler_table, inc_table,
1235                                  compiler, CompLevel(task()->comp_level()));
1236     }
1237     // Free codeBlobs
1238     code_buffer->free_blob();
1239 
1240     if (nm != nullptr) {
1241       nm->set_has_unsafe_access(has_unsafe_access);
1242       nm->set_has_wide_vectors(has_wide_vectors);
1243       nm->set_has_monitors(has_monitors);
1244       nm->set_has_scoped_access(has_scoped_access);
1245       nm->set_preloaded(false);
1246       nm->set_has_clinit_barriers(has_clinit_barriers);
1247       assert(!method->is_synchronized() || nm->has_monitors(), "");
1248 
1249 #if INCLUDE_CDS
1250       if (task()->is_precompile()) {
1251         AOTCodeEntry* aot_code_entry = AOTCodeCache::store_nmethod(nm, compiler, for_preload);
1252         if (aot_code_entry != nullptr) {
1253           aot_code_entry->set_inlined_bytecodes(num_inlined_bytecodes());
1254         }
1255       }
1256 #endif
1257       make_code_usable(THREAD, target, /* preload */ false, entry_bci, /* aot_code_entry */ nullptr, nm);
1258     }
1259   }
1260 
1261   NoSafepointVerifier nsv;
1262   if (nm != nullptr) {
1263     // Compilation succeeded, post what we know about it
1264     nm->post_compiled_method(task());
1265     task()->set_num_inlined_bytecodes(num_inlined_bytecodes());
1266   } else if (install_code) {
1267     // The CodeCache is full.
1268     record_failure("code cache is full");
1269   } else {
1270     task()->set_num_inlined_bytecodes(num_inlined_bytecodes());
1271   }
1272 
1273   // safepoints are allowed again
1274 }
1275 
1276 // ------------------------------------------------------------------
1277 // ciEnv::find_system_klass
1278 ciKlass* ciEnv::find_system_klass(ciSymbol* klass_name) {
1279   VM_ENTRY_MARK;
1280   return get_klass_by_name_impl(nullptr, constantPoolHandle(), klass_name, false);
1281 }
1282 
1283 // ------------------------------------------------------------------
1284 // ciEnv::comp_level
1285 int ciEnv::comp_level() {
1286   if (task() == nullptr)  return CompilationPolicy::highest_compile_level();
1287   return task()->comp_level();
1288 }
1289 
1290 // ------------------------------------------------------------------
1291 // ciEnv::compile_id
1292 int ciEnv::compile_id() {
1293   if (task() == nullptr)  return 0;
1294   return task()->compile_id();
1295 }
1296 
1297 // ------------------------------------------------------------------
1298 // ciEnv::notice_inlined_method()
1299 void ciEnv::notice_inlined_method(ciMethod* method) {
1300   _num_inlined_bytecodes += method->code_size_for_inlining();
1301   CompileTrainingData* ctd = task()->training_data();
1302   if (ctd != nullptr) {
1303     GUARDED_VM_ENTRY({
1304       methodHandle mh(Thread::current(), method->get_Method());
1305       ctd->notice_inlined_method(task(), mh);
1306     });
1307   }
1308 }
1309 
1310 // ------------------------------------------------------------------
1311 // ciEnv::num_inlined_bytecodes()
1312 int ciEnv::num_inlined_bytecodes() const {
1313   return _num_inlined_bytecodes;
1314 }
1315 
1316 // ------------------------------------------------------------------
1317 // ciEnv::record_failure()
1318 void ciEnv::record_failure(const char* reason) {
1319   // record the bailout for hserr envlog
1320   if (reason != nullptr) {
1321     if (CompilationLog::log() != nullptr) {
1322       CompilerThread* thread = CompilerThread::current();
1323       CompileTask* task = thread->task();
1324       CompilationLog::log()->log_failure(thread, task, reason, nullptr);
1325     }
1326   }
1327 
1328   if (_failure_reason.get() == nullptr) {
1329     // Record the first failure reason.
1330     _failure_reason.set(reason);
1331   }
1332 }
1333 
1334 void ciEnv::report_failure(const char* reason) {
1335   EventCompilationFailure event;
1336   if (event.should_commit()) {
1337     CompilerEvent::CompilationFailureEvent::post(event, compile_id(), reason);
1338   }
1339 }
1340 
1341 // ------------------------------------------------------------------
1342 // ciEnv::record_method_not_compilable()
1343 void ciEnv::record_method_not_compilable(const char* reason, bool all_tiers) {
1344   int new_compilable =
1345     all_tiers ? MethodCompilable_never : MethodCompilable_not_at_tier ;
1346 
1347   // Only note transitions to a worse state
1348   if (new_compilable > _compilable) {
1349     if (log() != nullptr) {
1350       if (all_tiers) {
1351         log()->elem("method_not_compilable");
1352       } else {
1353         log()->elem("method_not_compilable_at_tier level='%d'",
1354                     current()->task()->comp_level());
1355       }
1356     }
1357     _compilable = new_compilable;
1358 
1359     // Reset failure reason; this one is more important.
1360     _failure_reason.clear();
1361     record_failure(reason);
1362   }
1363 }
1364 
1365 // ------------------------------------------------------------------
1366 // ciEnv::record_out_of_memory_failure()
1367 void ciEnv::record_out_of_memory_failure() {
1368   // If memory is low, we stop compiling methods.
1369   record_method_not_compilable("out of memory");
1370 }
1371 
1372 ciInstance* ciEnv::unloaded_ciinstance() {
1373   GUARDED_VM_ENTRY(return _factory->get_unloaded_object_constant();)
1374 }
1375 
1376 // ------------------------------------------------------------------
1377 // Replay support
1378 
1379 
1380 // Lookup location descriptor for the class, if any.
1381 // Returns false if not found.
1382 bool ciEnv::dyno_loc(const InstanceKlass* ik, const char *&loc) const {
1383   bool found = false;
1384   int pos = _dyno_klasses->find_sorted<const InstanceKlass*, klass_compare>(ik, found);
1385   if (!found) {
1386     return false;
1387   }
1388   loc = _dyno_locs->at(pos);
1389   return found;
1390 }
1391 
1392 // Associate the current location descriptor with the given class and record for later lookup.
1393 void ciEnv::set_dyno_loc(const InstanceKlass* ik) {
1394   const char *loc = os::strdup(_dyno_name);
1395   bool found = false;
1396   int pos = _dyno_klasses->find_sorted<const InstanceKlass*, klass_compare>(ik, found);
1397   if (found) {
1398     _dyno_locs->at_put(pos, loc);
1399   } else {
1400     _dyno_klasses->insert_before(pos, ik);
1401     _dyno_locs->insert_before(pos, loc);
1402   }
1403 }
1404 
1405 // Associate the current location descriptor with the given class and record for later lookup.
1406 // If it turns out that there are multiple locations for the given class, that conflict should
1407 // be handled here.  Currently we choose the first location found.
1408 void ciEnv::record_best_dyno_loc(const InstanceKlass* ik) {
1409   if (!ik->is_hidden()) {
1410     return;
1411   }
1412   const char *loc0;
1413   if (!dyno_loc(ik, loc0)) {
1414     set_dyno_loc(ik);
1415   }
1416 }
1417 
1418 // Look up the location descriptor for the given class and print it to the output stream.
1419 bool ciEnv::print_dyno_loc(outputStream* out, const InstanceKlass* ik) const {
1420   const char *loc;
1421   if (dyno_loc(ik, loc)) {
1422     out->print("%s", loc);
1423     return true;
1424   } else {
1425     return false;
1426   }
1427 }
1428 
1429 // Look up the location descriptor for the given class and return it as a string.
1430 // Returns null if no location is found.
1431 const char *ciEnv::dyno_name(const InstanceKlass* ik) const {
1432   if (ik->is_hidden()) {
1433     stringStream ss;
1434     if (print_dyno_loc(&ss, ik)) {
1435       ss.print(" ;"); // add terminator
1436       const char* call_site = ss.as_string();
1437       return call_site;
1438     }
1439   }
1440   return nullptr;
1441 }
1442 
1443 // Look up the location descriptor for the given class and return it as a string.
1444 // Returns the class name as a fallback if no location is found.
1445 const char *ciEnv::replay_name(ciKlass* k) const {
1446   if (k->is_instance_klass()) {
1447     return replay_name(k->as_instance_klass()->get_instanceKlass());
1448   }
1449   return k->name()->as_quoted_ascii();
1450 }
1451 
1452 // Look up the location descriptor for the given class and return it as a string.
1453 // Returns the class name as a fallback if no location is found.
1454 const char *ciEnv::replay_name(const InstanceKlass* ik) const {
1455   const char* name = dyno_name(ik);
1456   if (name != nullptr) {
1457       return name;
1458   }
1459   return ik->name()->as_quoted_ascii();
1460 }
1461 
1462 // Process a java.lang.invoke.MemberName object and record any dynamic locations.
1463 void ciEnv::record_member(Thread* thread, oop member) {
1464   assert(java_lang_invoke_MemberName::is_instance(member), "!");
1465   // Check MemberName.clazz field
1466   oop clazz = java_lang_invoke_MemberName::clazz(member);
1467   if (clazz->klass()->is_instance_klass()) {
1468     RecordLocation fp(this, "clazz");
1469     InstanceKlass* ik = InstanceKlass::cast(clazz->klass());
1470     record_best_dyno_loc(ik);
1471   }
1472   // Check MemberName.method.vmtarget field
1473   Method* vmtarget = java_lang_invoke_MemberName::vmtarget(member);
1474   if (vmtarget != nullptr) {
1475     RecordLocation fp2(this, "<vmtarget>");
1476     InstanceKlass* ik = vmtarget->method_holder();
1477     record_best_dyno_loc(ik);
1478   }
1479 }
1480 
1481 // Read an object field.  Lookup is done by name only.
1482 static inline oop obj_field(oop obj, const char* name) {
1483     return ciReplay::obj_field(obj, name);
1484 }
1485 
1486 // Process a java.lang.invoke.LambdaForm object and record any dynamic locations.
1487 void ciEnv::record_lambdaform(Thread* thread, oop form) {
1488   assert(java_lang_invoke_LambdaForm::is_instance(form), "!");
1489 
1490   {
1491     // Check LambdaForm.vmentry field
1492     oop member = java_lang_invoke_LambdaForm::vmentry(form);
1493     RecordLocation fp0(this, "vmentry");
1494     record_member(thread, member);
1495   }
1496 
1497   // Check LambdaForm.names array
1498   objArrayOop names = (objArrayOop)obj_field(form, "names");
1499   if (names != nullptr) {
1500     RecordLocation lp0(this, "names");
1501     int len = names->length();
1502     for (int i = 0; i < len; ++i) {
1503       oop name = names->obj_at(i);
1504       RecordLocation lp1(this, "%d", i);
1505      // Check LambdaForm.names[i].function field
1506       RecordLocation lp2(this, "function");
1507       oop function = obj_field(name, "function");
1508       if (function != nullptr) {
1509         // Check LambdaForm.names[i].function.member field
1510         oop member = obj_field(function, "member");
1511         if (member != nullptr) {
1512           RecordLocation lp3(this, "member");
1513           record_member(thread, member);
1514         }
1515         // Check LambdaForm.names[i].function.resolvedHandle field
1516         oop mh = obj_field(function, "resolvedHandle");
1517         if (mh != nullptr) {
1518           RecordLocation lp3(this, "resolvedHandle");
1519           record_mh(thread, mh);
1520         }
1521         // Check LambdaForm.names[i].function.invoker field
1522         oop invoker = obj_field(function, "invoker");
1523         if (invoker != nullptr) {
1524           RecordLocation lp3(this, "invoker");
1525           record_mh(thread, invoker);
1526         }
1527       }
1528     }
1529   }
1530 }
1531 
1532 // Process a java.lang.invoke.MethodHandle object and record any dynamic locations.
1533 void ciEnv::record_mh(Thread* thread, oop mh) {
1534   {
1535     // Check MethodHandle.form field
1536     oop form = java_lang_invoke_MethodHandle::form(mh);
1537     RecordLocation fp(this, "form");
1538     record_lambdaform(thread, form);
1539   }
1540   // Check DirectMethodHandle.member field
1541   if (java_lang_invoke_DirectMethodHandle::is_instance(mh)) {
1542     oop member = java_lang_invoke_DirectMethodHandle::member(mh);
1543     RecordLocation fp(this, "member");
1544     record_member(thread, member);
1545   } else {
1546     // Check <MethodHandle subclass>.argL<n> fields
1547     // Probably BoundMethodHandle.Species_L*, but we only care if the field exists
1548     char arg_name[] = "argLXX";
1549     int max_arg = 99;
1550     for (int index = 0; index <= max_arg; ++index) {
1551       jio_snprintf(arg_name, sizeof (arg_name), "argL%d", index);
1552       oop arg = obj_field(mh, arg_name);
1553       if (arg != nullptr) {
1554         RecordLocation fp(this, "%s", arg_name);
1555         if (arg->klass()->is_instance_klass()) {
1556           InstanceKlass* ik2 = InstanceKlass::cast(arg->klass());
1557           record_best_dyno_loc(ik2);
1558           record_call_site_obj(thread, arg);
1559         }
1560       } else {
1561         break;
1562       }
1563     }
1564   }
1565 }
1566 
1567 // Process an object found at an invokedynamic/invokehandle call site and record any dynamic locations.
1568 // Types currently supported are MethodHandle and CallSite.
1569 // The object is typically the "appendix" object, or Bootstrap Method (BSM) object.
1570 void ciEnv::record_call_site_obj(Thread* thread, oop obj)
1571 {
1572   if (obj != nullptr) {
1573     if (java_lang_invoke_MethodHandle::is_instance(obj)) {
1574         record_mh(thread, obj);
1575     } else if (java_lang_invoke_ConstantCallSite::is_instance(obj)) {
1576       oop target = java_lang_invoke_CallSite::target(obj);
1577       if (target->klass()->is_instance_klass()) {
1578         RecordLocation fp(this, "target");
1579         InstanceKlass* ik = InstanceKlass::cast(target->klass());
1580         record_best_dyno_loc(ik);
1581       }
1582     }
1583   }
1584 }
1585 
1586 // Process an adapter Method* found at an invokedynamic/invokehandle call site and record any dynamic locations.
1587 void ciEnv::record_call_site_method(Thread* thread, Method* adapter) {
1588   InstanceKlass* holder = adapter->method_holder();
1589   if (!holder->is_hidden()) {
1590     return;
1591   }
1592   RecordLocation fp(this, "<adapter>");
1593   record_best_dyno_loc(holder);
1594 }
1595 
1596 // Process an invokedynamic call site and record any dynamic locations.
1597 void ciEnv::process_invokedynamic(const constantPoolHandle &cp, int indy_index, JavaThread* thread) {
1598   ResolvedIndyEntry* indy_info = cp->resolved_indy_entry_at(indy_index);
1599   if (indy_info->method() != nullptr) {
1600     // process the adapter
1601     Method* adapter = indy_info->method();
1602     record_call_site_method(thread, adapter);
1603     // process the appendix
1604     oop appendix = cp->resolved_reference_from_indy(indy_index);
1605     {
1606       RecordLocation fp(this, "<appendix>");
1607       record_call_site_obj(thread, appendix);
1608     }
1609     // process the BSM
1610     int pool_index = indy_info->constant_pool_index();
1611     BootstrapInfo bootstrap_specifier(cp, pool_index, indy_index);
1612     oop bsm = cp->resolve_possibly_cached_constant_at(bootstrap_specifier.bsm_index(), thread);
1613     {
1614       RecordLocation fp(this, "<bsm>");
1615       record_call_site_obj(thread, bsm);
1616     }
1617   }
1618 }
1619 
1620 // Process an invokehandle call site and record any dynamic locations.
1621 void ciEnv::process_invokehandle(const constantPoolHandle &cp, int index, JavaThread* thread) {
1622   const int holder_index = cp->klass_ref_index_at(index, Bytecodes::_invokehandle);
1623   if (!cp->tag_at(holder_index).is_klass()) {
1624     return;  // not resolved
1625   }
1626   Klass* holder = ConstantPool::klass_at_if_loaded(cp, holder_index);
1627   Symbol* name = cp->name_ref_at(index, Bytecodes::_invokehandle);
1628   if (MethodHandles::is_signature_polymorphic_name(holder, name)) {
1629     ResolvedMethodEntry* method_entry = cp->resolved_method_entry_at(index);
1630     if (method_entry->is_resolved(Bytecodes::_invokehandle)) {
1631       // process the adapter
1632       Method* adapter = method_entry->method();
1633       oop appendix = cp->cache()->appendix_if_resolved(method_entry);
1634       record_call_site_method(thread, adapter);
1635       // process the appendix
1636       {
1637         RecordLocation fp(this, "<appendix>");
1638         record_call_site_obj(thread, appendix);
1639       }
1640     }
1641   }
1642 }
1643 
1644 // Search the class hierarchy for dynamic classes reachable through dynamic call sites or
1645 // constant pool entries and record for future lookup.
1646 void ciEnv::find_dynamic_call_sites() {
1647   _dyno_klasses = new (arena()) GrowableArray<const InstanceKlass*>(arena(), 100, 0, nullptr);
1648   _dyno_locs    = new (arena()) GrowableArray<const char *>(arena(), 100, 0, nullptr);
1649 
1650   // Iterate over the class hierarchy
1651   for (ClassHierarchyIterator iter(vmClasses::Object_klass()); !iter.done(); iter.next()) {
1652     Klass* sub = iter.klass();
1653     if (sub->is_instance_klass()) {
1654       InstanceKlass *isub = InstanceKlass::cast(sub);
1655       InstanceKlass* ik = isub;
1656       if (!ik->is_linked()) {
1657         continue;
1658       }
1659       if (ik->is_hidden()) {
1660         continue;
1661       }
1662       JavaThread* thread = JavaThread::current();
1663       const constantPoolHandle pool(thread, ik->constants());
1664 
1665       // Look for invokedynamic/invokehandle call sites
1666       for (int i = 0; i < ik->methods()->length(); ++i) {
1667         Method* m = ik->methods()->at(i);
1668 
1669         BytecodeStream bcs(methodHandle(thread, m));
1670         while (!bcs.is_last_bytecode()) {
1671           Bytecodes::Code opcode = bcs.next();
1672           opcode = bcs.raw_code();
1673           switch (opcode) {
1674           case Bytecodes::_invokedynamic:
1675           case Bytecodes::_invokehandle: {
1676             RecordLocation fp(this, "@bci %s %s %s %d",
1677                          ik->name()->as_quoted_ascii(),
1678                          m->name()->as_quoted_ascii(), m->signature()->as_quoted_ascii(),
1679                          bcs.bci());
1680             if (opcode == Bytecodes::_invokedynamic) {
1681               int index = bcs.get_index_u4();
1682               process_invokedynamic(pool, index, thread);
1683             } else {
1684               assert(opcode == Bytecodes::_invokehandle, "new switch label added?");
1685               int cp_cache_index = bcs.get_index_u2();
1686               process_invokehandle(pool, cp_cache_index, thread);
1687             }
1688             break;
1689           }
1690           default:
1691             break;
1692           }
1693         }
1694       }
1695 
1696       // Look for MethodHandle constant pool entries
1697       RecordLocation fp(this, "@cpi %s", ik->name()->as_quoted_ascii());
1698       int len = pool->length();
1699       for (int i = 0; i < len; ++i) {
1700         if (pool->tag_at(i).is_method_handle()) {
1701           bool found_it;
1702           oop mh = pool->find_cached_constant_at(i, found_it, thread);
1703           if (mh != nullptr) {
1704             RecordLocation fp(this, "%d", i);
1705             record_mh(thread, mh);
1706           }
1707         }
1708       }
1709     }
1710   }
1711 }
1712 
1713 void ciEnv::dump_compile_data(outputStream* out) {
1714   CompileTask* task = this->task();
1715   if (task) {
1716 #ifdef COMPILER2
1717     if (ReplayReduce && compiler_data() != nullptr) {
1718       // Dump C2 "reduced" inlining data.
1719       ((Compile*)compiler_data())->dump_inline_data_reduced(out);
1720     }
1721 #endif
1722     Method* method = task->method();
1723     int entry_bci = task->osr_bci();
1724     int comp_level = task->comp_level();
1725     out->print("compile ");
1726     get_method(method)->dump_name_as_ascii(out);
1727     out->print(" %d %d", entry_bci, comp_level);
1728     if (compiler_data() != nullptr) {
1729       if (is_c2_compile(comp_level)) {
1730 #ifdef COMPILER2
1731         // Dump C2 inlining data.
1732         ((Compile*)compiler_data())->dump_inline_data(out);
1733 #endif
1734       } else if (is_c1_compile(comp_level)) {
1735 #ifdef COMPILER1
1736         // Dump C1 inlining data.
1737         ((Compilation*)compiler_data())->dump_inline_data(out);
1738 #endif
1739       }
1740     }
1741     out->cr();
1742   }
1743 }
1744 
1745 // Called from VM error reporter, so be careful.
1746 // Don't safepoint or acquire any locks.
1747 //
1748 void ciEnv::dump_replay_data_helper(outputStream* out) {
1749   NoSafepointVerifier no_safepoint;
1750   ResourceMark rm;
1751 
1752   assert(this->task() != nullptr, "task must not be null");
1753 
1754   dump_replay_data_version(out);
1755 #if INCLUDE_JVMTI
1756   out->print_cr("JvmtiExport can_access_local_variables %d",     _jvmti_can_access_local_variables);
1757   out->print_cr("JvmtiExport can_hotswap_or_post_breakpoint %d", _jvmti_can_hotswap_or_post_breakpoint);
1758   out->print_cr("JvmtiExport can_post_on_exceptions %d",         _jvmti_can_post_on_exceptions);
1759 #endif // INCLUDE_JVMTI
1760 
1761   find_dynamic_call_sites();
1762 
1763   GrowableArray<ciMetadata*>* objects = _factory->get_ci_metadata();
1764   out->print_cr("# %d ciObject found", objects->length());
1765 
1766   // The very first entry is the InstanceKlass of the root method of the current compilation.
1767   ciInstanceKlass::dump_replay_instanceKlass(out, task()->method()->method_holder());
1768 
1769   for (int i = 0; i < objects->length(); i++) {
1770     objects->at(i)->dump_replay_data(out);
1771   }
1772 
1773   dump_compile_data(out);
1774   out->flush();
1775 }
1776 
1777 // Called from VM error reporter, so be careful.
1778 // Don't safepoint or acquire any locks.
1779 //
1780 void ciEnv::dump_replay_data_unsafe(outputStream* out) {
1781   GUARDED_VM_ENTRY(
1782     dump_replay_data_helper(out);
1783   )
1784 }
1785 
1786 void ciEnv::dump_replay_data(outputStream* out) {
1787   GUARDED_VM_ENTRY(
1788     MutexLocker ml(Compile_lock);
1789     dump_replay_data_helper(out);
1790   )
1791 }
1792 
1793 void ciEnv::dump_replay_data(int compile_id) {
1794   char buffer[64];
1795   int ret = jio_snprintf(buffer, sizeof(buffer), "replay_pid%d_compid%d.log", os::current_process_id(), compile_id);
1796   if (ret > 0) {
1797     int fd = os::open(buffer, O_RDWR | O_CREAT | O_TRUNC, 0666);
1798     if (fd != -1) {
1799       FILE* replay_data_file = os::fdopen(fd, "w");
1800       if (replay_data_file != nullptr) {
1801         fileStream replay_data_stream(replay_data_file, /*need_close=*/true);
1802         dump_replay_data(&replay_data_stream);
1803         tty->print_cr("# Compiler replay data is saved as: %s", buffer);
1804       } else {
1805         tty->print_cr("# Can't open file to dump replay data.");
1806         close(fd);
1807       }
1808     }
1809   }
1810 }
1811 
1812 void ciEnv::dump_inline_data(int compile_id) {
1813   char buffer[64];
1814   int ret = jio_snprintf(buffer, sizeof(buffer), "inline_pid%d_compid%d.log", os::current_process_id(), compile_id);
1815   if (ret > 0) {
1816     int fd = os::open(buffer, O_RDWR | O_CREAT | O_TRUNC, 0666);
1817     if (fd != -1) {
1818       FILE* inline_data_file = os::fdopen(fd, "w");
1819       if (inline_data_file != nullptr) {
1820         fileStream replay_data_stream(inline_data_file, /*need_close=*/true);
1821         GUARDED_VM_ENTRY(
1822           MutexLocker ml(Compile_lock);
1823           dump_replay_data_version(&replay_data_stream);
1824           dump_compile_data(&replay_data_stream);
1825         )
1826         replay_data_stream.flush();
1827         tty->print("# Compiler inline data is saved as: ");
1828         tty->print_cr("%s", buffer);
1829       } else {
1830         tty->print_cr("# Can't open file to dump inline data.");
1831         close(fd);
1832       }
1833     }
1834   }
1835 }
1836 
1837 void ciEnv::dump_replay_data_version(outputStream* out) {
1838   out->print_cr("version %d", REPLAY_VERSION);
1839 }
1840 
1841 bool ciEnv::is_precompile() {
1842   return (task() != nullptr) && task()->is_precompile();
1843 }
1844 
1845 InstanceKlass::ClassState ciEnv::compute_init_state_for_precompiled(InstanceKlass* ik) {
1846   ASSERT_IN_VM;
1847   ResourceMark rm;
1848   assert(is_precompile(), "should be called only for AOT compialtion in assembly phase");
1849   assert(!ik->is_in_error_state(), "comp_id: %d, klass %s", task()->compile_id(), ik->external_name());
1850 
1851   if (!AOTCacheAccess::can_generate_aot_code_for(ik)) {
1852     log_debug(precompile)("%d: klass (%s) %s is not archived", task()->compile_id(), InstanceKlass::state2name(ik->init_state()), ik->external_name());
1853     // Skip this class
1854     return InstanceKlass::ClassState::initialization_error;
1855   }
1856   if (task()->method()->method_holder() == ik) {
1857     log_trace(precompile)("%d: method_holder: (%s) %s", task()->compile_id(), InstanceKlass::state2name(ik->init_state()), ik->external_name());
1858     if (task()->method()->is_static_initializer()) { // Happens with -Xcomp
1859        return InstanceKlass::ClassState::being_initialized;
1860     } else {
1861        return InstanceKlass::ClassState::fully_initialized;
1862     }
1863   }
1864 
1865   switch (task()->compile_reason()) {
1866     case CompileTask::Reason_Precompile: {
1867       // Check init dependencies
1868       MethodTrainingData* mtd = nullptr;
1869       GUARDED_VM_ENTRY(mtd = MethodTrainingData::find(methodHandle(Thread::current(), task()->method())); )
1870       if (mtd != nullptr) {
1871         TrainingData::TrainingDataLocker l;
1872         CompileTrainingData* ctd = mtd->last_toplevel_compile(task()->comp_level());
1873         if (ctd != nullptr) {
1874           for (int i = 0; i < ctd->init_dep_count(); i++) {
1875             KlassTrainingData* ktd = ctd->init_dep(i);
1876             if (ktd->has_holder() && (ktd->holder() == ik)) {
1877               log_trace(precompile)("%d: init_dependency: (%s) %s", task()->compile_id(), InstanceKlass::state2name(ik->init_state()), ik->external_name());
1878               return InstanceKlass::ClassState::fully_initialized; // init dependency present
1879             }
1880           }
1881         }
1882       }
1883 
1884       // During AOT assembly and production runs CDS moves set of classes
1885       // into fully_initialized state before execution of Java bytecodes.
1886       if (AOTCacheAccess::is_early_aot_inited_class(ik)) {
1887         log_trace(precompile)("%d: early_aot_inited_class: (%s) %s", task()->compile_id(), InstanceKlass::state2name(ik->init_state()), ik->external_name());
1888         return InstanceKlass::ClassState::fully_initialized;
1889       }
1890 
1891       // Class may be not present during TD creation for this method.
1892       // It could happen when profiled data for inlined method
1893       // was updated after this method was compiled during training.
1894       break;
1895     }
1896     case CompileTask::Reason_PrecompileForPreload: {
1897       // Preload AOT code does not depend on Training Data,
1898       // it has class init barriers to initialize class by
1899       // going into interpreter or directly calling runtime.
1900       log_trace(precompile)("%d: for_preload: (%s) %s", task()->compile_id(), InstanceKlass::state2name(ik->init_state()), ik->external_name());
1901       return InstanceKlass::ClassState::fully_initialized;
1902     }
1903     default: fatal("%s", CompileTask::reason_name(task()->compile_reason()));
1904   }
1905   log_debug(precompile)("%d: klass (%s) %s is not recorded for this compilation", task()->compile_id(), InstanceKlass::state2name(ik->init_state()), ik->external_name());
1906   // Skip this class
1907   return InstanceKlass::ClassState::initialization_error;
1908 }