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