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