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