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/compilerEvent.hpp"
  47 #include "compiler/compileLog.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 }
1169 
1170 // ------------------------------------------------------------------
1171 // ciEnv::num_inlined_bytecodes()
1172 int ciEnv::num_inlined_bytecodes() const {
1173   return _num_inlined_bytecodes;
1174 }
1175 
1176 // ------------------------------------------------------------------
1177 // ciEnv::record_failure()
1178 void ciEnv::record_failure(const char* reason) {
1179   if (_failure_reason.get() == nullptr) {
1180     // Record the first failure reason.
1181     _failure_reason.set(reason);
1182   }
1183 }
1184 
1185 void ciEnv::report_failure(const char* reason) {
1186   EventCompilationFailure event;
1187   if (event.should_commit()) {
1188     CompilerEvent::CompilationFailureEvent::post(event, compile_id(), reason);
1189   }
1190 }
1191 
1192 // ------------------------------------------------------------------
1193 // ciEnv::record_method_not_compilable()
1194 void ciEnv::record_method_not_compilable(const char* reason, bool all_tiers) {
1195   int new_compilable =
1196     all_tiers ? MethodCompilable_never : MethodCompilable_not_at_tier ;
1197 
1198   // Only note transitions to a worse state
1199   if (new_compilable > _compilable) {
1200     if (log() != nullptr) {
1201       if (all_tiers) {
1202         log()->elem("method_not_compilable");
1203       } else {
1204         log()->elem("method_not_compilable_at_tier level='%d'",
1205                     current()->task()->comp_level());
1206       }
1207     }
1208     _compilable = new_compilable;
1209 
1210     // Reset failure reason; this one is more important.
1211     _failure_reason.clear();
1212     record_failure(reason);
1213   }
1214 }
1215 
1216 // ------------------------------------------------------------------
1217 // ciEnv::record_out_of_memory_failure()
1218 void ciEnv::record_out_of_memory_failure() {
1219   // If memory is low, we stop compiling methods.
1220   record_method_not_compilable("out of memory");
1221 }
1222 
1223 ciInstance* ciEnv::unloaded_ciinstance() {
1224   GUARDED_VM_ENTRY(return _factory->get_unloaded_object_constant();)
1225 }
1226 
1227 // ------------------------------------------------------------------
1228 // Replay support
1229 
1230 
1231 // Lookup location descriptor for the class, if any.
1232 // Returns false if not found.
1233 bool ciEnv::dyno_loc(const InstanceKlass* ik, const char *&loc) const {
1234   bool found = false;
1235   int pos = _dyno_klasses->find_sorted<const InstanceKlass*, klass_compare>(ik, found);
1236   if (!found) {
1237     return false;
1238   }
1239   loc = _dyno_locs->at(pos);
1240   return found;
1241 }
1242 
1243 // Associate the current location descriptor with the given class and record for later lookup.
1244 void ciEnv::set_dyno_loc(const InstanceKlass* ik) {
1245   const char *loc = os::strdup(_dyno_name);
1246   bool found = false;
1247   int pos = _dyno_klasses->find_sorted<const InstanceKlass*, klass_compare>(ik, found);
1248   if (found) {
1249     _dyno_locs->at_put(pos, loc);
1250   } else {
1251     _dyno_klasses->insert_before(pos, ik);
1252     _dyno_locs->insert_before(pos, loc);
1253   }
1254 }
1255 
1256 // Associate the current location descriptor with the given class and record for later lookup.
1257 // If it turns out that there are multiple locations for the given class, that conflict should
1258 // be handled here.  Currently we choose the first location found.
1259 void ciEnv::record_best_dyno_loc(const InstanceKlass* ik) {
1260   if (!ik->is_hidden()) {
1261     return;
1262   }
1263   const char *loc0;
1264   if (!dyno_loc(ik, loc0)) {
1265     set_dyno_loc(ik);
1266   }
1267 }
1268 
1269 // Look up the location descriptor for the given class and print it to the output stream.
1270 bool ciEnv::print_dyno_loc(outputStream* out, const InstanceKlass* ik) const {
1271   const char *loc;
1272   if (dyno_loc(ik, loc)) {
1273     out->print("%s", loc);
1274     return true;
1275   } else {
1276     return false;
1277   }
1278 }
1279 
1280 // Look up the location descriptor for the given class and return it as a string.
1281 // Returns null if no location is found.
1282 const char *ciEnv::dyno_name(const InstanceKlass* ik) const {
1283   if (ik->is_hidden()) {
1284     stringStream ss;
1285     if (print_dyno_loc(&ss, ik)) {
1286       ss.print(" ;"); // add terminator
1287       const char* call_site = ss.as_string();
1288       return call_site;
1289     }
1290   }
1291   return nullptr;
1292 }
1293 
1294 // Look up the location descriptor for the given class and return it as a string.
1295 // Returns the class name as a fallback if no location is found.
1296 const char *ciEnv::replay_name(ciKlass* k) const {
1297   if (k->is_instance_klass()) {
1298     return replay_name(k->as_instance_klass()->get_instanceKlass());
1299   }
1300   return k->name()->as_quoted_ascii();
1301 }
1302 
1303 // Look up the location descriptor for the given class and return it as a string.
1304 // Returns the class name as a fallback if no location is found.
1305 const char *ciEnv::replay_name(const InstanceKlass* ik) const {
1306   const char* name = dyno_name(ik);
1307   if (name != nullptr) {
1308       return name;
1309   }
1310   return ik->name()->as_quoted_ascii();
1311 }
1312 
1313 // Process a java.lang.invoke.MemberName object and record any dynamic locations.
1314 void ciEnv::record_member(Thread* thread, oop member) {
1315   assert(java_lang_invoke_MemberName::is_instance(member), "!");
1316   // Check MemberName.clazz field
1317   oop clazz = java_lang_invoke_MemberName::clazz(member);
1318   if (clazz->klass()->is_instance_klass()) {
1319     RecordLocation fp(this, "clazz");
1320     InstanceKlass* ik = InstanceKlass::cast(clazz->klass());
1321     record_best_dyno_loc(ik);
1322   }
1323   // Check MemberName.method.vmtarget field
1324   Method* vmtarget = java_lang_invoke_MemberName::vmtarget(member);
1325   if (vmtarget != nullptr) {
1326     RecordLocation fp2(this, "<vmtarget>");
1327     InstanceKlass* ik = vmtarget->method_holder();
1328     record_best_dyno_loc(ik);
1329   }
1330 }
1331 
1332 // Read an object field.  Lookup is done by name only.
1333 static inline oop obj_field(oop obj, const char* name) {
1334     return ciReplay::obj_field(obj, name);
1335 }
1336 
1337 // Process a java.lang.invoke.LambdaForm object and record any dynamic locations.
1338 void ciEnv::record_lambdaform(Thread* thread, oop form) {
1339   assert(java_lang_invoke_LambdaForm::is_instance(form), "!");
1340 
1341   {
1342     // Check LambdaForm.vmentry field
1343     oop member = java_lang_invoke_LambdaForm::vmentry(form);
1344     RecordLocation fp0(this, "vmentry");
1345     record_member(thread, member);
1346   }
1347 
1348   // Check LambdaForm.names array
1349   objArrayOop names = (objArrayOop)obj_field(form, "names");
1350   if (names != nullptr) {
1351     RecordLocation lp0(this, "names");
1352     int len = names->length();
1353     for (int i = 0; i < len; ++i) {
1354       oop name = names->obj_at(i);
1355       RecordLocation lp1(this, "%d", i);
1356      // Check LambdaForm.names[i].function field
1357       RecordLocation lp2(this, "function");
1358       oop function = obj_field(name, "function");
1359       if (function != nullptr) {
1360         // Check LambdaForm.names[i].function.member field
1361         oop member = obj_field(function, "member");
1362         if (member != nullptr) {
1363           RecordLocation lp3(this, "member");
1364           record_member(thread, member);
1365         }
1366         // Check LambdaForm.names[i].function.resolvedHandle field
1367         oop mh = obj_field(function, "resolvedHandle");
1368         if (mh != nullptr) {
1369           RecordLocation lp3(this, "resolvedHandle");
1370           record_mh(thread, mh);
1371         }
1372         // Check LambdaForm.names[i].function.invoker field
1373         oop invoker = obj_field(function, "invoker");
1374         if (invoker != nullptr) {
1375           RecordLocation lp3(this, "invoker");
1376           record_mh(thread, invoker);
1377         }
1378       }
1379     }
1380   }
1381 }
1382 
1383 // Process a java.lang.invoke.MethodHandle object and record any dynamic locations.
1384 void ciEnv::record_mh(Thread* thread, oop mh) {
1385   {
1386     // Check MethodHandle.form field
1387     oop form = java_lang_invoke_MethodHandle::form(mh);
1388     RecordLocation fp(this, "form");
1389     record_lambdaform(thread, form);
1390   }
1391   // Check DirectMethodHandle.member field
1392   if (java_lang_invoke_DirectMethodHandle::is_instance(mh)) {
1393     oop member = java_lang_invoke_DirectMethodHandle::member(mh);
1394     RecordLocation fp(this, "member");
1395     record_member(thread, member);
1396   } else {
1397     // Check <MethodHandle subclass>.argL<n> fields
1398     // Probably BoundMethodHandle.Species_L*, but we only care if the field exists
1399     char arg_name[] = "argLXX";
1400     int max_arg = 99;
1401     for (int index = 0; index <= max_arg; ++index) {
1402       jio_snprintf(arg_name, sizeof (arg_name), "argL%d", index);
1403       oop arg = obj_field(mh, arg_name);
1404       if (arg != nullptr) {
1405         RecordLocation fp(this, "%s", arg_name);
1406         if (arg->klass()->is_instance_klass()) {
1407           InstanceKlass* ik2 = InstanceKlass::cast(arg->klass());
1408           record_best_dyno_loc(ik2);
1409           record_call_site_obj(thread, arg);
1410         }
1411       } else {
1412         break;
1413       }
1414     }
1415   }
1416 }
1417 
1418 // Process an object found at an invokedynamic/invokehandle call site and record any dynamic locations.
1419 // Types currently supported are MethodHandle and CallSite.
1420 // The object is typically the "appendix" object, or Bootstrap Method (BSM) object.
1421 void ciEnv::record_call_site_obj(Thread* thread, oop obj)
1422 {
1423   if (obj != nullptr) {
1424     if (java_lang_invoke_MethodHandle::is_instance(obj)) {
1425         record_mh(thread, obj);
1426     } else if (java_lang_invoke_ConstantCallSite::is_instance(obj)) {
1427       oop target = java_lang_invoke_CallSite::target(obj);
1428       if (target->klass()->is_instance_klass()) {
1429         RecordLocation fp(this, "target");
1430         InstanceKlass* ik = InstanceKlass::cast(target->klass());
1431         record_best_dyno_loc(ik);
1432       }
1433     }
1434   }
1435 }
1436 
1437 // Process an adapter Method* found at an invokedynamic/invokehandle call site and record any dynamic locations.
1438 void ciEnv::record_call_site_method(Thread* thread, Method* adapter) {
1439   InstanceKlass* holder = adapter->method_holder();
1440   if (!holder->is_hidden()) {
1441     return;
1442   }
1443   RecordLocation fp(this, "<adapter>");
1444   record_best_dyno_loc(holder);
1445 }
1446 
1447 // Process an invokedynamic call site and record any dynamic locations.
1448 void ciEnv::process_invokedynamic(const constantPoolHandle &cp, int indy_index, JavaThread* thread) {
1449   ResolvedIndyEntry* indy_info = cp->resolved_indy_entry_at(indy_index);
1450   if (indy_info->method() != nullptr) {
1451     // process the adapter
1452     Method* adapter = indy_info->method();
1453     record_call_site_method(thread, adapter);
1454     // process the appendix
1455     oop appendix = cp->resolved_reference_from_indy(indy_index);
1456     {
1457       RecordLocation fp(this, "<appendix>");
1458       record_call_site_obj(thread, appendix);
1459     }
1460     // process the BSM
1461     int pool_index = indy_info->constant_pool_index();
1462     BootstrapInfo bootstrap_specifier(cp, pool_index, indy_index);
1463     oop bsm = cp->resolve_possibly_cached_constant_at(bootstrap_specifier.bsm_index(), thread);
1464     {
1465       RecordLocation fp(this, "<bsm>");
1466       record_call_site_obj(thread, bsm);
1467     }
1468   }
1469 }
1470 
1471 // Process an invokehandle call site and record any dynamic locations.
1472 void ciEnv::process_invokehandle(const constantPoolHandle &cp, int index, JavaThread* thread) {
1473   const int holder_index = cp->klass_ref_index_at(index, Bytecodes::_invokehandle);
1474   if (!cp->tag_at(holder_index).is_klass()) {
1475     return;  // not resolved
1476   }
1477   Klass* holder = ConstantPool::klass_at_if_loaded(cp, holder_index);
1478   Symbol* name = cp->name_ref_at(index, Bytecodes::_invokehandle);
1479   if (MethodHandles::is_signature_polymorphic_name(holder, name)) {
1480     ResolvedMethodEntry* method_entry = cp->resolved_method_entry_at(index);
1481     if (method_entry->is_resolved(Bytecodes::_invokehandle)) {
1482       // process the adapter
1483       Method* adapter = method_entry->method();
1484       oop appendix = cp->cache()->appendix_if_resolved(method_entry);
1485       record_call_site_method(thread, adapter);
1486       // process the appendix
1487       {
1488         RecordLocation fp(this, "<appendix>");
1489         record_call_site_obj(thread, appendix);
1490       }
1491     }
1492   }
1493 }
1494 
1495 // Search the class hierarchy for dynamic classes reachable through dynamic call sites or
1496 // constant pool entries and record for future lookup.
1497 void ciEnv::find_dynamic_call_sites() {
1498   _dyno_klasses = new (arena()) GrowableArray<const InstanceKlass*>(arena(), 100, 0, nullptr);
1499   _dyno_locs    = new (arena()) GrowableArray<const char *>(arena(), 100, 0, nullptr);
1500 
1501   // Iterate over the class hierarchy
1502   for (ClassHierarchyIterator iter(vmClasses::Object_klass()); !iter.done(); iter.next()) {
1503     Klass* sub = iter.klass();
1504     if (sub->is_instance_klass()) {
1505       InstanceKlass *isub = InstanceKlass::cast(sub);
1506       InstanceKlass* ik = isub;
1507       if (!ik->is_linked()) {
1508         continue;
1509       }
1510       if (ik->is_hidden()) {
1511         continue;
1512       }
1513       JavaThread* thread = JavaThread::current();
1514       const constantPoolHandle pool(thread, ik->constants());
1515 
1516       // Look for invokedynamic/invokehandle call sites
1517       for (int i = 0; i < ik->methods()->length(); ++i) {
1518         Method* m = ik->methods()->at(i);
1519 
1520         BytecodeStream bcs(methodHandle(thread, m));
1521         while (!bcs.is_last_bytecode()) {
1522           Bytecodes::Code opcode = bcs.next();
1523           opcode = bcs.raw_code();
1524           switch (opcode) {
1525           case Bytecodes::_invokedynamic:
1526           case Bytecodes::_invokehandle: {
1527             RecordLocation fp(this, "@bci %s %s %s %d",
1528                          ik->name()->as_quoted_ascii(),
1529                          m->name()->as_quoted_ascii(), m->signature()->as_quoted_ascii(),
1530                          bcs.bci());
1531             if (opcode == Bytecodes::_invokedynamic) {
1532               int index = bcs.get_index_u4();
1533               process_invokedynamic(pool, index, thread);
1534             } else {
1535               assert(opcode == Bytecodes::_invokehandle, "new switch label added?");
1536               int cp_cache_index = bcs.get_index_u2();
1537               process_invokehandle(pool, cp_cache_index, thread);
1538             }
1539             break;
1540           }
1541           default:
1542             break;
1543           }
1544         }
1545       }
1546 
1547       // Look for MethodHandle constant pool entries
1548       RecordLocation fp(this, "@cpi %s", ik->name()->as_quoted_ascii());
1549       int len = pool->length();
1550       for (int i = 0; i < len; ++i) {
1551         if (pool->tag_at(i).is_method_handle()) {
1552           bool found_it;
1553           oop mh = pool->find_cached_constant_at(i, found_it, thread);
1554           if (mh != nullptr) {
1555             RecordLocation fp(this, "%d", i);
1556             record_mh(thread, mh);
1557           }
1558         }
1559       }
1560     }
1561   }
1562 }
1563 
1564 void ciEnv::dump_compile_data(outputStream* out) {
1565   CompileTask* task = this->task();
1566   if (task) {
1567 #ifdef COMPILER2
1568     if (ReplayReduce && compiler_data() != nullptr) {
1569       // Dump C2 "reduced" inlining data.
1570       ((Compile*)compiler_data())->dump_inline_data_reduced(out);
1571     }
1572 #endif
1573     Method* method = task->method();
1574     int entry_bci = task->osr_bci();
1575     int comp_level = task->comp_level();
1576     out->print("compile ");
1577     get_method(method)->dump_name_as_ascii(out);
1578     out->print(" %d %d", entry_bci, comp_level);
1579     if (compiler_data() != nullptr) {
1580       if (is_c2_compile(comp_level)) {
1581 #ifdef COMPILER2
1582         // Dump C2 inlining data.
1583         ((Compile*)compiler_data())->dump_inline_data(out);
1584 #endif
1585       } else if (is_c1_compile(comp_level)) {
1586 #ifdef COMPILER1
1587         // Dump C1 inlining data.
1588         ((Compilation*)compiler_data())->dump_inline_data(out);
1589 #endif
1590       }
1591     }
1592     out->cr();
1593   }
1594 }
1595 
1596 // Called from VM error reporter, so be careful.
1597 // Don't safepoint or acquire any locks.
1598 //
1599 void ciEnv::dump_replay_data_helper(outputStream* out) {
1600   NoSafepointVerifier no_safepoint;
1601   ResourceMark rm;
1602 
1603   assert(this->task() != nullptr, "task must not be null");
1604 
1605   dump_replay_data_version(out);
1606 #if INCLUDE_JVMTI
1607   out->print_cr("JvmtiExport can_access_local_variables %d",     _jvmti_can_access_local_variables);
1608   out->print_cr("JvmtiExport can_hotswap_or_post_breakpoint %d", _jvmti_can_hotswap_or_post_breakpoint);
1609   out->print_cr("JvmtiExport can_post_on_exceptions %d",         _jvmti_can_post_on_exceptions);
1610 #endif // INCLUDE_JVMTI
1611 
1612   find_dynamic_call_sites();
1613 
1614   GrowableArray<ciMetadata*>* objects = _factory->get_ci_metadata();
1615   out->print_cr("# %d ciObject found", objects->length());
1616 
1617   // The very first entry is the InstanceKlass of the root method of the current compilation.
1618   ciInstanceKlass::dump_replay_instanceKlass(out, task()->method()->method_holder());
1619 
1620   for (int i = 0; i < objects->length(); i++) {
1621     objects->at(i)->dump_replay_data(out);
1622   }
1623 
1624   dump_compile_data(out);
1625   out->flush();
1626 }
1627 
1628 // Called from VM error reporter, so be careful.
1629 // Don't safepoint or acquire any locks.
1630 //
1631 void ciEnv::dump_replay_data_unsafe(outputStream* out) {
1632   GUARDED_VM_ENTRY(
1633     dump_replay_data_helper(out);
1634   )
1635 }
1636 
1637 void ciEnv::dump_replay_data(outputStream* out) {
1638   GUARDED_VM_ENTRY(
1639     MutexLocker ml(Compile_lock);
1640     dump_replay_data_helper(out);
1641   )
1642 }
1643 
1644 void ciEnv::dump_replay_data(int compile_id) {
1645   char buffer[64];
1646   int ret = jio_snprintf(buffer, sizeof(buffer), "replay_pid%d_compid%d.log", os::current_process_id(), compile_id);
1647   if (ret > 0) {
1648     int fd = os::open(buffer, O_RDWR | O_CREAT | O_TRUNC, 0666);
1649     if (fd != -1) {
1650       FILE* replay_data_file = os::fdopen(fd, "w");
1651       if (replay_data_file != nullptr) {
1652         fileStream replay_data_stream(replay_data_file, /*need_close=*/true);
1653         dump_replay_data(&replay_data_stream);
1654         tty->print_cr("# Compiler replay data is saved as: %s", buffer);
1655       } else {
1656         tty->print_cr("# Can't open file to dump replay data.");
1657         close(fd);
1658       }
1659     }
1660   }
1661 }
1662 
1663 void ciEnv::dump_inline_data(int compile_id) {
1664   char buffer[64];
1665   int ret = jio_snprintf(buffer, sizeof(buffer), "inline_pid%d_compid%d.log", os::current_process_id(), compile_id);
1666   if (ret > 0) {
1667     int fd = os::open(buffer, O_RDWR | O_CREAT | O_TRUNC, 0666);
1668     if (fd != -1) {
1669       FILE* inline_data_file = os::fdopen(fd, "w");
1670       if (inline_data_file != nullptr) {
1671         fileStream replay_data_stream(inline_data_file, /*need_close=*/true);
1672         GUARDED_VM_ENTRY(
1673           MutexLocker ml(Compile_lock);
1674           dump_replay_data_version(&replay_data_stream);
1675           dump_compile_data(&replay_data_stream);
1676         )
1677         replay_data_stream.flush();
1678         tty->print("# Compiler inline data is saved as: ");
1679         tty->print_cr("%s", buffer);
1680       } else {
1681         tty->print_cr("# Can't open file to dump inline data.");
1682         close(fd);
1683       }
1684     }
1685   }
1686 }
1687 
1688 void ciEnv::dump_replay_data_version(outputStream* out) {
1689   out->print_cr("version %d", REPLAY_VERSION);
1690 }
--- EOF ---