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