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