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