1 /*
   2  * Copyright (c) 1999, 2020, 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/ciUtilities.inline.hpp"
  36 #include "classfile/symbolTable.hpp"
  37 #include "classfile/systemDictionary.hpp"
  38 #include "classfile/vmSymbols.hpp"
  39 #include "code/codeCache.hpp"
  40 #include "code/scopeDesc.hpp"
  41 #include "compiler/compileBroker.hpp"
  42 #include "compiler/compilerEvent.hpp"
  43 #include "compiler/compileLog.hpp"
  44 #include "compiler/compileTask.hpp"
  45 #include "compiler/disassembler.hpp"
  46 #include "gc/shared/collectedHeap.inline.hpp"
  47 #include "interpreter/linkResolver.hpp"
  48 #include "jfr/jfrEvents.hpp"
  49 #include "logging/log.hpp"
  50 #include "memory/allocation.inline.hpp"
  51 #include "memory/oopFactory.hpp"
  52 #include "memory/resourceArea.hpp"
  53 #include "memory/universe.hpp"
  54 #include "oops/constantPool.inline.hpp"
  55 #include "oops/cpCache.inline.hpp"
  56 #include "oops/method.inline.hpp"
  57 #include "oops/methodData.hpp"
  58 #include "oops/objArrayKlass.hpp"
  59 #include "oops/objArrayOop.inline.hpp"
  60 #include "oops/oop.inline.hpp"
  61 #include "prims/jvmtiExport.hpp"
  62 #include "runtime/handles.inline.hpp"
  63 #include "runtime/init.hpp"
  64 #include "runtime/reflection.hpp"
  65 #include "runtime/jniHandles.inline.hpp"
  66 #include "runtime/safepointVerifiers.hpp"
  67 #include "runtime/sharedRuntime.hpp"
  68 #include "runtime/thread.inline.hpp"
  69 #include "utilities/dtrace.hpp"
  70 #include "utilities/macros.hpp"
  71 #ifdef COMPILER1
  72 #include "c1/c1_Runtime1.hpp"
  73 #endif
  74 #ifdef COMPILER2
  75 #include "opto/runtime.hpp"
  76 #endif
  77 
  78 // ciEnv
  79 //
  80 // This class is the top level broker for requests from the compiler
  81 // to the VM.
  82 
  83 ciObject*              ciEnv::_null_object_instance;
  84 
  85 #define WK_KLASS_DEFN(name, ignore_s) ciInstanceKlass* ciEnv::_##name = NULL;
  86 WK_KLASSES_DO(WK_KLASS_DEFN)
  87 #undef WK_KLASS_DEFN
  88 
  89 ciSymbol*        ciEnv::_unloaded_cisymbol = NULL;
  90 ciInstanceKlass* ciEnv::_unloaded_ciinstance_klass = NULL;
  91 ciObjArrayKlass* ciEnv::_unloaded_ciobjarrayklass = NULL;
  92 
  93 jobject ciEnv::_ArrayIndexOutOfBoundsException_handle = NULL;
  94 jobject ciEnv::_ArrayStoreException_handle = NULL;
  95 jobject ciEnv::_ClassCastException_handle = NULL;
  96 
  97 #ifndef PRODUCT
  98 static bool firstEnv = true;
  99 #endif /* PRODUCT */
 100 
 101 // ------------------------------------------------------------------
 102 // ciEnv::ciEnv
 103 ciEnv::ciEnv(CompileTask* task)
 104   : _ciEnv_arena(mtCompiler) {
 105   VM_ENTRY_MARK;
 106 
 107   // Set up ciEnv::current immediately, for the sake of ciObjectFactory, etc.
 108   thread->set_env(this);
 109   assert(ciEnv::current() == this, "sanity");
 110 
 111   _oop_recorder = NULL;
 112   _debug_info = NULL;
 113   _dependencies = NULL;
 114   _failure_reason = NULL;
 115   _inc_decompile_count_on_failure = true;
 116   _compilable = MethodCompilable;
 117   _break_at_compile = false;
 118   _compiler_data = NULL;
 119 #ifndef PRODUCT
 120   assert(!firstEnv, "not initialized properly");
 121 #endif /* !PRODUCT */
 122 
 123   _num_inlined_bytecodes = 0;
 124   assert(task == NULL || thread->task() == task, "sanity");
 125   if (task != NULL) {
 126     task->mark_started(os::elapsed_counter());
 127   }
 128   _task = task;
 129   _log = NULL;
 130 
 131   // Temporary buffer for creating symbols and such.
 132   _name_buffer = NULL;
 133   _name_buffer_len = 0;
 134 
 135   _arena   = &_ciEnv_arena;
 136   _factory = new (_arena) ciObjectFactory(_arena, 128);
 137 
 138   // Preload commonly referenced system ciObjects.
 139 
 140   // During VM initialization, these instances have not yet been created.
 141   // Assertions ensure that these instances are not accessed before
 142   // their initialization.
 143 
 144   assert(Universe::is_fully_initialized(), "should be complete");
 145 
 146   oop o = Universe::null_ptr_exception_instance();
 147   assert(o != NULL, "should have been initialized");
 148   _NullPointerException_instance = get_object(o)->as_instance();
 149   o = Universe::arithmetic_exception_instance();
 150   assert(o != NULL, "should have been initialized");
 151   _ArithmeticException_instance = get_object(o)->as_instance();
 152 
 153   _ArrayIndexOutOfBoundsException_instance = NULL;
 154   _ArrayStoreException_instance = NULL;
 155   _ClassCastException_instance = NULL;
 156   _the_null_string = NULL;
 157   _the_min_jint_string = NULL;
 158 
 159   _jvmti_redefinition_count = 0;
 160   _jvmti_can_hotswap_or_post_breakpoint = false;
 161   _jvmti_can_access_local_variables = false;
 162   _jvmti_can_post_on_exceptions = false;
 163   _jvmti_can_pop_frame = false;
 164 }
 165 
 166 ciEnv::ciEnv(Arena* arena) : _ciEnv_arena(mtCompiler) {
 167   ASSERT_IN_VM;
 168 
 169   // Set up ciEnv::current immediately, for the sake of ciObjectFactory, etc.
 170   CompilerThread* current_thread = CompilerThread::current();
 171   assert(current_thread->env() == NULL, "must be");
 172   current_thread->set_env(this);
 173   assert(ciEnv::current() == this, "sanity");
 174 
 175   _oop_recorder = NULL;
 176   _debug_info = NULL;
 177   _dependencies = NULL;
 178   _failure_reason = NULL;
 179   _inc_decompile_count_on_failure = true;
 180   _compilable = MethodCompilable_never;
 181   _break_at_compile = false;
 182   _compiler_data = NULL;
 183 #ifndef PRODUCT
 184   assert(firstEnv, "must be first");
 185   firstEnv = false;
 186 #endif /* !PRODUCT */
 187 
 188   _num_inlined_bytecodes = 0;
 189   _task = NULL;
 190   _log = NULL;
 191 
 192   // Temporary buffer for creating symbols and such.
 193   _name_buffer = NULL;
 194   _name_buffer_len = 0;
 195 
 196   _arena   = arena;
 197   _factory = new (_arena) ciObjectFactory(_arena, 128);
 198 
 199   // Preload commonly referenced system ciObjects.
 200 
 201   // During VM initialization, these instances have not yet been created.
 202   // Assertions ensure that these instances are not accessed before
 203   // their initialization.
 204 
 205   assert(Universe::is_fully_initialized(), "must be");
 206 
 207   _NullPointerException_instance = NULL;
 208   _ArithmeticException_instance = NULL;
 209   _ArrayIndexOutOfBoundsException_instance = NULL;
 210   _ArrayStoreException_instance = NULL;
 211   _ClassCastException_instance = NULL;
 212   _the_null_string = NULL;
 213   _the_min_jint_string = NULL;
 214 
 215   _jvmti_redefinition_count = 0;
 216   _jvmti_can_hotswap_or_post_breakpoint = false;
 217   _jvmti_can_access_local_variables = false;
 218   _jvmti_can_post_on_exceptions = false;
 219   _jvmti_can_pop_frame = false;
 220 }
 221 
 222 ciEnv::~ciEnv() {
 223   GUARDED_VM_ENTRY(
 224       CompilerThread* current_thread = CompilerThread::current();
 225       _factory->remove_symbols();
 226       // Need safepoint to clear the env on the thread.  RedefineClasses might
 227       // be reading it.
 228       current_thread->set_env(NULL);
 229   )
 230 }
 231 
 232 // ------------------------------------------------------------------
 233 // Cache Jvmti state
 234 bool ciEnv::cache_jvmti_state() {
 235   VM_ENTRY_MARK;
 236   // Get Jvmti capabilities under lock to get consistant values.
 237   MutexLocker mu(JvmtiThreadState_lock);
 238   _jvmti_redefinition_count             = JvmtiExport::redefinition_count();
 239   _jvmti_can_hotswap_or_post_breakpoint = JvmtiExport::can_hotswap_or_post_breakpoint();
 240   _jvmti_can_access_local_variables     = JvmtiExport::can_access_local_variables();
 241   _jvmti_can_post_on_exceptions         = JvmtiExport::can_post_on_exceptions();
 242   _jvmti_can_pop_frame                  = JvmtiExport::can_pop_frame();
 243   _jvmti_can_get_owned_monitor_info     = JvmtiExport::can_get_owned_monitor_info();
 244   _jvmti_can_walk_any_space             = JvmtiExport::can_walk_any_space();
 245   return _task != NULL && _task->method()->is_old();
 246 }
 247 
 248 bool ciEnv::jvmti_state_changed() const {
 249   // Some classes were redefined
 250   if (_jvmti_redefinition_count != JvmtiExport::redefinition_count()) {
 251     return true;
 252   }
 253 
 254   if (!_jvmti_can_access_local_variables &&
 255       JvmtiExport::can_access_local_variables()) {
 256     return true;
 257   }
 258   if (!_jvmti_can_hotswap_or_post_breakpoint &&
 259       JvmtiExport::can_hotswap_or_post_breakpoint()) {
 260     return true;
 261   }
 262   if (!_jvmti_can_post_on_exceptions &&
 263       JvmtiExport::can_post_on_exceptions()) {
 264     return true;
 265   }
 266   if (!_jvmti_can_pop_frame &&
 267       JvmtiExport::can_pop_frame()) {
 268     return true;
 269   }
 270   if (!_jvmti_can_get_owned_monitor_info &&
 271       JvmtiExport::can_get_owned_monitor_info()) {
 272     return true;
 273   }
 274   if (!_jvmti_can_walk_any_space &&
 275       JvmtiExport::can_walk_any_space()) {
 276     return true;
 277   }
 278 
 279   return false;
 280 }
 281 
 282 // ------------------------------------------------------------------
 283 // Cache DTrace flags
 284 void ciEnv::cache_dtrace_flags() {
 285   // Need lock?
 286   _dtrace_extended_probes = ExtendedDTraceProbes;
 287   if (_dtrace_extended_probes) {
 288     _dtrace_monitor_probes  = true;
 289     _dtrace_method_probes   = true;
 290     _dtrace_alloc_probes    = true;
 291   } else {
 292     _dtrace_monitor_probes  = DTraceMonitorProbes;
 293     _dtrace_method_probes   = DTraceMethodProbes;
 294     _dtrace_alloc_probes    = DTraceAllocProbes;
 295   }
 296 }
 297 
 298 // ------------------------------------------------------------------
 299 // helper for lazy exception creation
 300 ciInstance* ciEnv::get_or_create_exception(jobject& handle, Symbol* name) {
 301   VM_ENTRY_MARK;
 302   if (handle == NULL) {
 303     // Cf. universe.cpp, creation of Universe::_null_ptr_exception_instance.
 304     Klass* k = SystemDictionary::find(name, Handle(), Handle(), THREAD);
 305     jobject objh = NULL;
 306     if (!HAS_PENDING_EXCEPTION && k != NULL) {
 307       oop obj = InstanceKlass::cast(k)->allocate_instance(THREAD);
 308       if (!HAS_PENDING_EXCEPTION)
 309         objh = JNIHandles::make_global(Handle(THREAD, obj));
 310     }
 311     if (HAS_PENDING_EXCEPTION) {
 312       CLEAR_PENDING_EXCEPTION;
 313     } else {
 314       handle = objh;
 315     }
 316   }
 317   oop obj = JNIHandles::resolve(handle);
 318   return obj == NULL? NULL: get_object(obj)->as_instance();
 319 }
 320 
 321 ciInstance* ciEnv::ArrayIndexOutOfBoundsException_instance() {
 322   if (_ArrayIndexOutOfBoundsException_instance == NULL) {
 323     _ArrayIndexOutOfBoundsException_instance
 324           = get_or_create_exception(_ArrayIndexOutOfBoundsException_handle,
 325           vmSymbols::java_lang_ArrayIndexOutOfBoundsException());
 326   }
 327   return _ArrayIndexOutOfBoundsException_instance;
 328 }
 329 ciInstance* ciEnv::ArrayStoreException_instance() {
 330   if (_ArrayStoreException_instance == NULL) {
 331     _ArrayStoreException_instance
 332           = get_or_create_exception(_ArrayStoreException_handle,
 333           vmSymbols::java_lang_ArrayStoreException());
 334   }
 335   return _ArrayStoreException_instance;
 336 }
 337 ciInstance* ciEnv::ClassCastException_instance() {
 338   if (_ClassCastException_instance == NULL) {
 339     _ClassCastException_instance
 340           = get_or_create_exception(_ClassCastException_handle,
 341           vmSymbols::java_lang_ClassCastException());
 342   }
 343   return _ClassCastException_instance;
 344 }
 345 
 346 ciInstance* ciEnv::the_null_string() {
 347   if (_the_null_string == NULL) {
 348     VM_ENTRY_MARK;
 349     _the_null_string = get_object(Universe::the_null_string())->as_instance();
 350   }
 351   return _the_null_string;
 352 }
 353 
 354 ciInstance* ciEnv::the_min_jint_string() {
 355   if (_the_min_jint_string == NULL) {
 356     VM_ENTRY_MARK;
 357     _the_min_jint_string = get_object(Universe::the_min_jint_string())->as_instance();
 358   }
 359   return _the_min_jint_string;
 360 }
 361 
 362 // ------------------------------------------------------------------
 363 // ciEnv::get_method_from_handle
 364 ciMethod* ciEnv::get_method_from_handle(Method* method) {
 365   VM_ENTRY_MARK;
 366   return get_metadata(method)->as_method();
 367 }
 368 
 369 // ------------------------------------------------------------------
 370 // ciEnv::array_element_offset_in_bytes
 371 int ciEnv::array_element_offset_in_bytes(ciArray* a_h, ciObject* o_h) {
 372   VM_ENTRY_MARK;
 373   objArrayOop a = (objArrayOop)a_h->get_oop();
 374   assert(a->is_objArray(), "");
 375   int length = a->length();
 376   oop o = o_h->get_oop();
 377   for (int i = 0; i < length; i++) {
 378     if (a->obj_at(i) == o)  return i;
 379   }
 380   return -1;
 381 }
 382 
 383 
 384 // ------------------------------------------------------------------
 385 // ciEnv::check_klass_accessiblity
 386 //
 387 // Note: the logic of this method should mirror the logic of
 388 // ConstantPool::verify_constant_pool_resolve.
 389 bool ciEnv::check_klass_accessibility(ciKlass* accessing_klass,
 390                                       Klass* resolved_klass) {
 391   if (accessing_klass == NULL || !accessing_klass->is_loaded()) {
 392     return true;
 393   }
 394   if (accessing_klass->is_obj_array_klass()) {
 395     accessing_klass = accessing_klass->as_obj_array_klass()->base_element_klass();
 396   }
 397   if (!accessing_klass->is_instance_klass()) {
 398     return true;
 399   }
 400 
 401   if (resolved_klass->is_objArray_klass()) {
 402     // Find the element klass, if this is an array.
 403     resolved_klass = ObjArrayKlass::cast(resolved_klass)->bottom_klass();
 404   }
 405   if (resolved_klass->is_instance_klass()) {
 406     return (Reflection::verify_class_access(accessing_klass->get_Klass(),
 407                                             InstanceKlass::cast(resolved_klass),
 408                                             true) == Reflection::ACCESS_OK);
 409   }
 410   return true;
 411 }
 412 
 413 // ------------------------------------------------------------------
 414 // ciEnv::get_klass_by_name_impl
 415 ciKlass* ciEnv::get_klass_by_name_impl(ciKlass* accessing_klass,
 416                                        const constantPoolHandle& cpool,
 417                                        ciSymbol* name,
 418                                        bool require_local) {
 419   ASSERT_IN_VM;
 420   EXCEPTION_CONTEXT;
 421 
 422   // Now we need to check the SystemDictionary
 423   Symbol* sym = name->get_symbol();
 424   if (Signature::has_envelope(sym)) {
 425     // This is a name from a signature.  Strip off the trimmings.
 426     // Call recursive to keep scope of strippedsym.
 427     TempNewSymbol strippedsym = Signature::strip_envelope(sym);
 428     ciSymbol* strippedname = get_symbol(strippedsym);
 429     return get_klass_by_name_impl(accessing_klass, cpool, strippedname, require_local);
 430   }
 431 
 432   // Check for prior unloaded klass.  The SystemDictionary's answers
 433   // can vary over time but the compiler needs consistency.
 434   ciKlass* unloaded_klass = check_get_unloaded_klass(accessing_klass, name);
 435   if (unloaded_klass != NULL) {
 436     if (require_local)  return NULL;
 437     return unloaded_klass;
 438   }
 439 
 440   Handle loader(THREAD, (oop)NULL);
 441   Handle domain(THREAD, (oop)NULL);
 442   if (accessing_klass != NULL) {
 443     loader = Handle(THREAD, accessing_klass->loader());
 444     domain = Handle(THREAD, accessing_klass->protection_domain());
 445   }
 446 
 447   // setup up the proper type to return on OOM
 448   ciKlass* fail_type;
 449   if (sym->char_at(0) == JVM_SIGNATURE_ARRAY) {
 450     fail_type = _unloaded_ciobjarrayklass;
 451   } else {
 452     fail_type = _unloaded_ciinstance_klass;
 453   }
 454   Klass* found_klass;
 455   {
 456     ttyUnlocker ttyul;  // release tty lock to avoid ordering problems
 457     MutexLocker ml(Compile_lock);
 458     Klass* kls;
 459     if (!require_local) {
 460       kls = SystemDictionary::find_constrained_instance_or_array_klass(sym, loader,
 461                                                                        KILL_COMPILE_ON_FATAL_(fail_type));
 462     } else {
 463       kls = SystemDictionary::find_instance_or_array_klass(sym, loader, domain,
 464                                                            KILL_COMPILE_ON_FATAL_(fail_type));
 465     }
 466     found_klass = kls;
 467   }
 468 
 469   // If we fail to find an array klass, look again for its element type.
 470   // The element type may be available either locally or via constraints.
 471   // In either case, if we can find the element type in the system dictionary,
 472   // we must build an array type around it.  The CI requires array klasses
 473   // to be loaded if their element klasses are loaded, except when memory
 474   // is exhausted.
 475   if (Signature::is_array(sym) &&
 476       (sym->char_at(1) == JVM_SIGNATURE_ARRAY || sym->char_at(1) == JVM_SIGNATURE_CLASS)) {
 477     // We have an unloaded array.
 478     // Build it on the fly if the element class exists.
 479     SignatureStream ss(sym, false);
 480     ss.skip_array_prefix(1);
 481     // Get element ciKlass recursively.
 482     ciKlass* elem_klass =
 483       get_klass_by_name_impl(accessing_klass,
 484                              cpool,
 485                              get_symbol(ss.as_symbol()),
 486                              require_local);
 487     if (elem_klass != NULL && elem_klass->is_loaded()) {
 488       // Now make an array for it
 489       return ciObjArrayKlass::make_impl(elem_klass);
 490     }
 491   }
 492 
 493   if (found_klass == NULL && !cpool.is_null() && cpool->has_preresolution()) {
 494     // Look inside the constant pool for pre-resolved class entries.
 495     for (int i = cpool->length() - 1; i >= 1; i--) {
 496       if (cpool->tag_at(i).is_klass()) {
 497         Klass* kls = cpool->resolved_klass_at(i);
 498         if (kls->name() == sym) {
 499           found_klass = kls;
 500           break;
 501         }
 502       }
 503     }
 504   }
 505 
 506   if (found_klass != NULL) {
 507     // Found it.  Build a CI handle.
 508     return get_klass(found_klass);
 509   }
 510 
 511   if (require_local)  return NULL;
 512 
 513   // Not yet loaded into the VM, or not governed by loader constraints.
 514   // Make a CI representative for it.
 515   return get_unloaded_klass(accessing_klass, name);
 516 }
 517 
 518 // ------------------------------------------------------------------
 519 // ciEnv::get_klass_by_name
 520 ciKlass* ciEnv::get_klass_by_name(ciKlass* accessing_klass,
 521                                   ciSymbol* klass_name,
 522                                   bool require_local) {
 523   GUARDED_VM_ENTRY(return get_klass_by_name_impl(accessing_klass,
 524                                                  constantPoolHandle(),
 525                                                  klass_name,
 526                                                  require_local);)
 527 }
 528 
 529 // ------------------------------------------------------------------
 530 // ciEnv::get_klass_by_index_impl
 531 //
 532 // Implementation of get_klass_by_index.
 533 ciKlass* ciEnv::get_klass_by_index_impl(const constantPoolHandle& cpool,
 534                                         int index,
 535                                         bool& is_accessible,
 536                                         ciInstanceKlass* accessor) {
 537   EXCEPTION_CONTEXT;
 538   Klass* klass = NULL;
 539   Symbol* klass_name = NULL;
 540 
 541   if (cpool->tag_at(index).is_symbol()) {
 542     klass_name = cpool->symbol_at(index);
 543   } else {
 544     // Check if it's resolved if it's not a symbol constant pool entry.
 545     klass =  ConstantPool::klass_at_if_loaded(cpool, index);
 546     // Try to look it up by name.
 547     if (klass == NULL) {
 548       klass_name = cpool->klass_name_at(index);
 549     }
 550   }
 551 
 552   if (klass == NULL) {
 553     // Not found in constant pool.  Use the name to do the lookup.
 554     ciKlass* k = get_klass_by_name_impl(accessor,
 555                                         cpool,
 556                                         get_symbol(klass_name),
 557                                         false);
 558     // Calculate accessibility the hard way.
 559     if (!k->is_loaded()) {
 560       is_accessible = false;
 561     } else if (k->loader() != accessor->loader() &&
 562                get_klass_by_name_impl(accessor, cpool, k->name(), true) == NULL) {
 563       // Loaded only remotely.  Not linked yet.
 564       is_accessible = false;
 565     } else {
 566       // Linked locally, and we must also check public/private, etc.
 567       is_accessible = check_klass_accessibility(accessor, k->get_Klass());
 568     }
 569     return k;
 570   }
 571 
 572   // Check for prior unloaded klass.  The SystemDictionary's answers
 573   // can vary over time but the compiler needs consistency.
 574   ciSymbol* name = get_symbol(klass->name());
 575   ciKlass* unloaded_klass = check_get_unloaded_klass(accessor, name);
 576   if (unloaded_klass != NULL) {
 577     is_accessible = false;
 578     return unloaded_klass;
 579   }
 580 
 581   // It is known to be accessible, since it was found in the constant pool.
 582   is_accessible = true;
 583   return get_klass(klass);
 584 }
 585 
 586 // ------------------------------------------------------------------
 587 // ciEnv::get_klass_by_index
 588 //
 589 // Get a klass from the constant pool.
 590 ciKlass* ciEnv::get_klass_by_index(const constantPoolHandle& cpool,
 591                                    int index,
 592                                    bool& is_accessible,
 593                                    ciInstanceKlass* accessor) {
 594   GUARDED_VM_ENTRY(return get_klass_by_index_impl(cpool, index, is_accessible, accessor);)
 595 }
 596 
 597 // ------------------------------------------------------------------
 598 // ciEnv::get_constant_by_index_impl
 599 //
 600 // Implementation of get_constant_by_index().
 601 ciConstant ciEnv::get_constant_by_index_impl(const constantPoolHandle& cpool,
 602                                              int pool_index, int cache_index,
 603                                              ciInstanceKlass* accessor) {
 604   bool ignore_will_link;
 605   EXCEPTION_CONTEXT;
 606   int index = pool_index;
 607   if (cache_index >= 0) {
 608     assert(index < 0, "only one kind of index at a time");
 609     index = cpool->object_to_cp_index(cache_index);
 610     oop obj = cpool->resolved_references()->obj_at(cache_index);
 611     if (obj != NULL) {
 612       if (obj == Universe::the_null_sentinel()) {
 613         return ciConstant(T_OBJECT, get_object(NULL));
 614       }
 615       BasicType bt = T_OBJECT;
 616       if (cpool->tag_at(index).is_dynamic_constant())
 617         bt = Signature::basic_type(cpool->uncached_signature_ref_at(index));
 618       if (is_reference_type(bt)) {
 619       } else {
 620         // we have to unbox the primitive value
 621         if (!is_java_primitive(bt))  return ciConstant();
 622         jvalue value;
 623         BasicType bt2 = java_lang_boxing_object::get_value(obj, &value);
 624         assert(bt2 == bt, "");
 625         switch (bt2) {
 626         case T_DOUBLE:  return ciConstant(value.d);
 627         case T_FLOAT:   return ciConstant(value.f);
 628         case T_LONG:    return ciConstant(value.j);
 629         case T_INT:     return ciConstant(bt2, value.i);
 630         case T_SHORT:   return ciConstant(bt2, value.s);
 631         case T_BYTE:    return ciConstant(bt2, value.b);
 632         case T_CHAR:    return ciConstant(bt2, value.c);
 633         case T_BOOLEAN: return ciConstant(bt2, value.z);
 634         default:  return ciConstant();
 635         }
 636       }
 637       ciObject* ciobj = get_object(obj);
 638       if (ciobj->is_array()) {
 639         return ciConstant(T_ARRAY, ciobj);
 640       } else {
 641         assert(ciobj->is_instance(), "should be an instance");
 642         return ciConstant(T_OBJECT, ciobj);
 643       }
 644     }
 645   }
 646   constantTag tag = cpool->tag_at(index);
 647   if (tag.is_int()) {
 648     return ciConstant(T_INT, (jint)cpool->int_at(index));
 649   } else if (tag.is_long()) {
 650     return ciConstant((jlong)cpool->long_at(index));
 651   } else if (tag.is_float()) {
 652     return ciConstant((jfloat)cpool->float_at(index));
 653   } else if (tag.is_double()) {
 654     return ciConstant((jdouble)cpool->double_at(index));
 655   } else if (tag.is_string()) {
 656     oop string = NULL;
 657     assert(cache_index >= 0, "should have a cache index");
 658     if (cpool->is_pseudo_string_at(index)) {
 659       string = cpool->pseudo_string_at(index, cache_index);
 660     } else {
 661       string = cpool->string_at(index, cache_index, THREAD);
 662       if (HAS_PENDING_EXCEPTION) {
 663         CLEAR_PENDING_EXCEPTION;
 664         record_out_of_memory_failure();
 665         return ciConstant();
 666       }
 667     }
 668     ciObject* constant = get_object(string);
 669     if (constant->is_array()) {
 670       return ciConstant(T_ARRAY, constant);
 671     } else {
 672       assert (constant->is_instance(), "must be an instance, or not? ");
 673       return ciConstant(T_OBJECT, constant);
 674     }
 675   } else if (tag.is_klass() || tag.is_unresolved_klass()) {
 676     // 4881222: allow ldc to take a class type
 677     ciKlass* klass = get_klass_by_index_impl(cpool, index, ignore_will_link, accessor);
 678     if (HAS_PENDING_EXCEPTION) {
 679       CLEAR_PENDING_EXCEPTION;
 680       record_out_of_memory_failure();
 681       return ciConstant();
 682     }
 683     assert (klass->is_instance_klass() || klass->is_array_klass(),
 684             "must be an instance or array klass ");
 685     return ciConstant(T_OBJECT, klass->java_mirror());
 686   } else if (tag.is_method_type()) {
 687     // must execute Java code to link this CP entry into cache[i].f1
 688     ciSymbol* signature = get_symbol(cpool->method_type_signature_at(index));
 689     ciObject* ciobj = get_unloaded_method_type_constant(signature);
 690     return ciConstant(T_OBJECT, ciobj);
 691   } else if (tag.is_method_handle()) {
 692     // must execute Java code to link this CP entry into cache[i].f1
 693     int ref_kind        = cpool->method_handle_ref_kind_at(index);
 694     int callee_index    = cpool->method_handle_klass_index_at(index);
 695     ciKlass* callee     = get_klass_by_index_impl(cpool, callee_index, ignore_will_link, accessor);
 696     ciSymbol* name      = get_symbol(cpool->method_handle_name_ref_at(index));
 697     ciSymbol* signature = get_symbol(cpool->method_handle_signature_ref_at(index));
 698     ciObject* ciobj     = get_unloaded_method_handle_constant(callee, name, signature, ref_kind);
 699     return ciConstant(T_OBJECT, ciobj);
 700   } else if (tag.is_dynamic_constant()) {
 701     return ciConstant();
 702   } else {
 703     ShouldNotReachHere();
 704     return ciConstant();
 705   }
 706 }
 707 
 708 // ------------------------------------------------------------------
 709 // ciEnv::get_constant_by_index
 710 //
 711 // Pull a constant out of the constant pool.  How appropriate.
 712 //
 713 // Implementation note: this query is currently in no way cached.
 714 ciConstant ciEnv::get_constant_by_index(const constantPoolHandle& cpool,
 715                                         int pool_index, int cache_index,
 716                                         ciInstanceKlass* accessor) {
 717   GUARDED_VM_ENTRY(return get_constant_by_index_impl(cpool, pool_index, cache_index, accessor);)
 718 }
 719 
 720 // ------------------------------------------------------------------
 721 // ciEnv::get_field_by_index_impl
 722 //
 723 // Implementation of get_field_by_index.
 724 //
 725 // Implementation note: the results of field lookups are cached
 726 // in the accessor klass.
 727 ciField* ciEnv::get_field_by_index_impl(ciInstanceKlass* accessor,
 728                                         int index) {
 729   ciConstantPoolCache* cache = accessor->field_cache();
 730   if (cache == NULL) {
 731     ciField* field = new (arena()) ciField(accessor, index);
 732     return field;
 733   } else {
 734     ciField* field = (ciField*)cache->get(index);
 735     if (field == NULL) {
 736       field = new (arena()) ciField(accessor, index);
 737       cache->insert(index, field);
 738     }
 739     return field;
 740   }
 741 }
 742 
 743 // ------------------------------------------------------------------
 744 // ciEnv::get_field_by_index
 745 //
 746 // Get a field by index from a klass's constant pool.
 747 ciField* ciEnv::get_field_by_index(ciInstanceKlass* accessor,
 748                                    int index) {
 749   GUARDED_VM_ENTRY(return get_field_by_index_impl(accessor, index);)
 750 }
 751 
 752 // ------------------------------------------------------------------
 753 // ciEnv::lookup_method
 754 //
 755 // Perform an appropriate method lookup based on accessor, holder,
 756 // name, signature, and bytecode.
 757 Method* ciEnv::lookup_method(ciInstanceKlass* accessor,
 758                              ciKlass*         holder,
 759                              Symbol*          name,
 760                              Symbol*          sig,
 761                              Bytecodes::Code  bc,
 762                              constantTag      tag) {
 763   // Accessibility checks are performed in ciEnv::get_method_by_index_impl.
 764   assert(check_klass_accessibility(accessor, holder->get_Klass()), "holder not accessible");
 765 
 766   InstanceKlass* accessor_klass = accessor->get_instanceKlass();
 767   Klass* holder_klass = holder->get_Klass();
 768   Method* dest_method;
 769   LinkInfo link_info(holder_klass, name, sig, accessor_klass, LinkInfo::AccessCheck::required, tag);
 770   switch (bc) {
 771   case Bytecodes::_invokestatic:
 772     dest_method =
 773       LinkResolver::resolve_static_call_or_null(link_info);
 774     break;
 775   case Bytecodes::_invokespecial:
 776     dest_method =
 777       LinkResolver::resolve_special_call_or_null(link_info);
 778     break;
 779   case Bytecodes::_invokeinterface:
 780     dest_method =
 781       LinkResolver::linktime_resolve_interface_method_or_null(link_info);
 782     break;
 783   case Bytecodes::_invokevirtual:
 784     dest_method =
 785       LinkResolver::linktime_resolve_virtual_method_or_null(link_info);
 786     break;
 787   default: ShouldNotReachHere();
 788   }
 789 
 790   return dest_method;
 791 }
 792 
 793 
 794 // ------------------------------------------------------------------
 795 // ciEnv::get_method_by_index_impl
 796 ciMethod* ciEnv::get_method_by_index_impl(const constantPoolHandle& cpool,
 797                                           int index, Bytecodes::Code bc,
 798                                           ciInstanceKlass* accessor) {
 799   assert(cpool.not_null(), "need constant pool");
 800   assert(accessor != NULL, "need origin of access");
 801   if (bc == Bytecodes::_invokedynamic) {
 802     ConstantPoolCacheEntry* cpce = cpool->invokedynamic_cp_cache_entry_at(index);
 803     bool is_resolved = !cpce->is_f1_null();
 804     // FIXME: code generation could allow for null (unlinked) call site
 805     // The call site could be made patchable as follows:
 806     // Load the appendix argument from the constant pool.
 807     // Test the appendix argument and jump to a known deopt routine if it is null.
 808     // Jump through a patchable call site, which is initially a deopt routine.
 809     // Patch the call site to the nmethod entry point of the static compiled lambda form.
 810     // As with other two-component call sites, both values must be independently verified.
 811 
 812     if (is_resolved) {
 813       // Get the invoker Method* from the constant pool.
 814       // (The appendix argument, if any, will be noted in the method's signature.)
 815       Method* adapter = cpce->f1_as_method();
 816       return get_method(adapter);
 817     }
 818 
 819     // Fake a method that is equivalent to a declared method.
 820     ciInstanceKlass* holder    = get_instance_klass(SystemDictionary::MethodHandle_klass());
 821     ciSymbol*        name      = ciSymbol::invokeBasic_name();
 822     ciSymbol*        signature = get_symbol(cpool->signature_ref_at(index));
 823     return get_unloaded_method(holder, name, signature, accessor);
 824   } else {
 825     const int holder_index = cpool->klass_ref_index_at(index);
 826     bool holder_is_accessible;
 827     ciKlass* holder = get_klass_by_index_impl(cpool, holder_index, holder_is_accessible, accessor);
 828 
 829     // Get the method's name and signature.
 830     Symbol* name_sym = cpool->name_ref_at(index);
 831     Symbol* sig_sym  = cpool->signature_ref_at(index);
 832 
 833     if (cpool->has_preresolution()
 834         || ((holder == ciEnv::MethodHandle_klass() || holder == ciEnv::VarHandle_klass()) &&
 835             MethodHandles::is_signature_polymorphic_name(holder->get_Klass(), name_sym))) {
 836       // Short-circuit lookups for JSR 292-related call sites.
 837       // That is, do not rely only on name-based lookups, because they may fail
 838       // if the names are not resolvable in the boot class loader (7056328).
 839       switch (bc) {
 840       case Bytecodes::_invokevirtual:
 841       case Bytecodes::_invokeinterface:
 842       case Bytecodes::_invokespecial:
 843       case Bytecodes::_invokestatic:
 844         {
 845           Method* m = ConstantPool::method_at_if_loaded(cpool, index);
 846           if (m != NULL) {
 847             return get_method(m);
 848           }
 849         }
 850         break;
 851       default:
 852         break;
 853       }
 854     }
 855 
 856     if (holder_is_accessible) {  // Our declared holder is loaded.
 857       constantTag tag = cpool->tag_ref_at(index);
 858       assert(accessor->get_instanceKlass() == cpool->pool_holder(), "not the pool holder?");
 859       Method* m = lookup_method(accessor, holder, name_sym, sig_sym, bc, tag);
 860       if (m != NULL &&
 861           (bc == Bytecodes::_invokestatic
 862            ?  m->method_holder()->is_not_initialized()
 863            : !m->method_holder()->is_loaded())) {
 864         m = NULL;
 865       }
 866 #ifdef ASSERT
 867       if (m != NULL && ReplayCompiles && !ciReplay::is_loaded(m)) {
 868         m = NULL;
 869       }
 870 #endif
 871       if (m != NULL) {
 872         // We found the method.
 873         return get_method(m);
 874       }
 875     }
 876 
 877     // Either the declared holder was not loaded, or the method could
 878     // not be found.  Create a dummy ciMethod to represent the failed
 879     // lookup.
 880     ciSymbol* name      = get_symbol(name_sym);
 881     ciSymbol* signature = get_symbol(sig_sym);
 882     return get_unloaded_method(holder, name, signature, accessor);
 883   }
 884 }
 885 
 886 
 887 // ------------------------------------------------------------------
 888 // ciEnv::get_instance_klass_for_declared_method_holder
 889 ciInstanceKlass* ciEnv::get_instance_klass_for_declared_method_holder(ciKlass* method_holder) {
 890   // For the case of <array>.clone(), the method holder can be a ciArrayKlass
 891   // instead of a ciInstanceKlass.  For that case simply pretend that the
 892   // declared holder is Object.clone since that's where the call will bottom out.
 893   // A more correct fix would trickle out through many interfaces in CI,
 894   // requiring ciInstanceKlass* to become ciKlass* and many more places would
 895   // require checks to make sure the expected type was found.  Given that this
 896   // only occurs for clone() the more extensive fix seems like overkill so
 897   // instead we simply smear the array type into Object.
 898   guarantee(method_holder != NULL, "no method holder");
 899   if (method_holder->is_instance_klass()) {
 900     return method_holder->as_instance_klass();
 901   } else if (method_holder->is_array_klass()) {
 902     return current()->Object_klass();
 903   } else {
 904     ShouldNotReachHere();
 905   }
 906   return NULL;
 907 }
 908 
 909 
 910 // ------------------------------------------------------------------
 911 // ciEnv::get_method_by_index
 912 ciMethod* ciEnv::get_method_by_index(const constantPoolHandle& cpool,
 913                                      int index, Bytecodes::Code bc,
 914                                      ciInstanceKlass* accessor) {
 915   GUARDED_VM_ENTRY(return get_method_by_index_impl(cpool, index, bc, accessor);)
 916 }
 917 
 918 
 919 // ------------------------------------------------------------------
 920 // ciEnv::name_buffer
 921 char *ciEnv::name_buffer(int req_len) {
 922   if (_name_buffer_len < req_len) {
 923     if (_name_buffer == NULL) {
 924       _name_buffer = (char*)arena()->Amalloc(sizeof(char)*req_len);
 925       _name_buffer_len = req_len;
 926     } else {
 927       _name_buffer =
 928         (char*)arena()->Arealloc(_name_buffer, _name_buffer_len, req_len);
 929       _name_buffer_len = req_len;
 930     }
 931   }
 932   return _name_buffer;
 933 }
 934 
 935 // ------------------------------------------------------------------
 936 // ciEnv::is_in_vm
 937 bool ciEnv::is_in_vm() {
 938   return JavaThread::current()->thread_state() == _thread_in_vm;
 939 }
 940 
 941 // ------------------------------------------------------------------
 942 // ciEnv::validate_compile_task_dependencies
 943 //
 944 // Check for changes during compilation (e.g. class loads, evolution,
 945 // breakpoints, call site invalidation).
 946 void ciEnv::validate_compile_task_dependencies(ciMethod* target) {
 947   if (failing())  return;  // no need for further checks
 948 
 949   Dependencies::DepType result = dependencies()->validate_dependencies(_task);
 950   if (result != Dependencies::end_marker) {
 951     if (result == Dependencies::call_site_target_value) {
 952       _inc_decompile_count_on_failure = false;
 953       record_failure("call site target change");
 954     } else if (Dependencies::is_klass_type(result)) {
 955       record_failure("concurrent class loading");
 956     } else {
 957       record_failure("invalid non-klass dependency");
 958     }
 959   }
 960 }
 961 
 962 // ------------------------------------------------------------------
 963 // ciEnv::register_method
 964 void ciEnv::register_method(ciMethod* target,
 965                             int entry_bci,
 966                             CodeOffsets* offsets,
 967                             int orig_pc_offset,
 968                             CodeBuffer* code_buffer,
 969                             int frame_words,
 970                             OopMapSet* oop_map_set,
 971                             ExceptionHandlerTable* handler_table,
 972                             ImplicitExceptionTable* inc_table,
 973                             AbstractCompiler* compiler,
 974                             bool has_unsafe_access,
 975                             bool has_wide_vectors,
 976                             RTMState  rtm_state) {
 977   VM_ENTRY_MARK;
 978   nmethod* nm = NULL;
 979   {
 980     // To prevent compile queue updates.
 981     MutexLocker locker(THREAD, MethodCompileQueue_lock);
 982 
 983     // Prevent SystemDictionary::add_to_hierarchy from running
 984     // and invalidating our dependencies until we install this method.
 985     // No safepoints are allowed. Otherwise, class redefinition can occur in between.
 986     MutexLocker ml(Compile_lock);
 987     NoSafepointVerifier nsv;
 988 
 989     // Change in Jvmti state may invalidate compilation.
 990     if (!failing() && jvmti_state_changed()) {
 991       record_failure("Jvmti state change invalidated dependencies");
 992     }
 993 
 994     // Change in DTrace flags may invalidate compilation.
 995     if (!failing() &&
 996         ( (!dtrace_extended_probes() && ExtendedDTraceProbes) ||
 997           (!dtrace_method_probes() && DTraceMethodProbes) ||
 998           (!dtrace_alloc_probes() && DTraceAllocProbes) )) {
 999       record_failure("DTrace flags change invalidated dependencies");
1000     }
1001 
1002     if (!failing() && target->needs_clinit_barrier() &&
1003         target->holder()->is_in_error_state()) {
1004       record_failure("method holder is in error state");
1005     }
1006 
1007     if (!failing()) {
1008       if (log() != NULL) {
1009         // Log the dependencies which this compilation declares.
1010         dependencies()->log_all_dependencies();
1011       }
1012 
1013       // Encode the dependencies now, so we can check them right away.
1014       dependencies()->encode_content_bytes();
1015 
1016       // Check for {class loads, evolution, breakpoints, ...} during compilation
1017       validate_compile_task_dependencies(target);
1018     }
1019 
1020     methodHandle method(THREAD, target->get_Method());
1021 
1022 #if INCLUDE_RTM_OPT
1023     if (!failing() && (rtm_state != NoRTM) &&
1024         (method()->method_data() != NULL) &&
1025         (method()->method_data()->rtm_state() != rtm_state)) {
1026       // Preemptive decompile if rtm state was changed.
1027       record_failure("RTM state change invalidated rtm code");
1028     }
1029 #endif
1030 
1031     if (failing()) {
1032       // While not a true deoptimization, it is a preemptive decompile.
1033       MethodData* mdo = method()->method_data();
1034       if (mdo != NULL && _inc_decompile_count_on_failure) {
1035         mdo->inc_decompile_count();
1036       }
1037 
1038       // All buffers in the CodeBuffer are allocated in the CodeCache.
1039       // If the code buffer is created on each compile attempt
1040       // as in C2, then it must be freed.
1041       code_buffer->free_blob();
1042       return;
1043     }
1044 
1045     assert(offsets->value(CodeOffsets::Deopt) != -1, "must have deopt entry");
1046     assert(offsets->value(CodeOffsets::Exceptions) != -1, "must have exception entry");
1047 
1048     nm =  nmethod::new_nmethod(method,
1049                                compile_id(),
1050                                entry_bci,
1051                                offsets,
1052                                orig_pc_offset,
1053                                debug_info(), dependencies(), code_buffer,
1054                                frame_words, oop_map_set,
1055                                handler_table, inc_table,
1056                                compiler, task()->comp_level());
1057 
1058     // Free codeBlobs
1059     code_buffer->free_blob();
1060 
1061     if (nm != NULL) {
1062       nm->set_has_unsafe_access(has_unsafe_access);
1063       nm->set_has_wide_vectors(has_wide_vectors);
1064 #if INCLUDE_RTM_OPT
1065       nm->set_rtm_state(rtm_state);
1066 #endif
1067 
1068       // Record successful registration.
1069       // (Put nm into the task handle *before* publishing to the Java heap.)
1070       if (task() != NULL) {
1071         task()->set_code(nm);
1072       }
1073 
1074       if (entry_bci == InvocationEntryBci) {
1075         if (TieredCompilation) {
1076           // If there is an old version we're done with it
1077           CompiledMethod* old = method->code();
1078           if (TraceMethodReplacement && old != NULL) {
1079             ResourceMark rm;
1080             char *method_name = method->name_and_sig_as_C_string();
1081             tty->print_cr("Replacing method %s", method_name);
1082           }
1083           if (old != NULL) {
1084             old->make_not_used();
1085           }
1086         }
1087 
1088         LogTarget(Info, nmethod, install) lt;
1089         if (lt.is_enabled()) {
1090           ResourceMark rm;
1091           char *method_name = method->name_and_sig_as_C_string();
1092           lt.print("Installing method (%d) %s ",
1093                     task()->comp_level(), method_name);
1094         }
1095         // Allow the code to be executed
1096         MutexLocker ml(CompiledMethod_lock, Mutex::_no_safepoint_check_flag);
1097         if (nm->make_in_use()) {
1098           method->set_code(method, nm);
1099         }
1100       } else {
1101         LogTarget(Info, nmethod, install) lt;
1102         if (lt.is_enabled()) {
1103           ResourceMark rm;
1104           char *method_name = method->name_and_sig_as_C_string();
1105           lt.print("Installing osr method (%d) %s @ %d",
1106                     task()->comp_level(), method_name, entry_bci);
1107         }
1108         MutexLocker ml(CompiledMethod_lock, Mutex::_no_safepoint_check_flag);
1109         if (nm->make_in_use()) {
1110           method->method_holder()->add_osr_nmethod(nm);
1111         }
1112       }
1113     }
1114   }  // safepoints are allowed again
1115 
1116   if (nm != NULL) {
1117     // JVMTI -- compiled method notification (must be done outside lock)
1118     nm->post_compiled_method_load_event();
1119   } else {
1120     // The CodeCache is full.
1121     record_failure("code cache is full");
1122   }
1123 }
1124 
1125 
1126 // ------------------------------------------------------------------
1127 // ciEnv::find_system_klass
1128 ciKlass* ciEnv::find_system_klass(ciSymbol* klass_name) {
1129   VM_ENTRY_MARK;
1130   return get_klass_by_name_impl(NULL, constantPoolHandle(), klass_name, false);
1131 }
1132 
1133 // ------------------------------------------------------------------
1134 // ciEnv::comp_level
1135 int ciEnv::comp_level() {
1136   if (task() == NULL)  return CompLevel_highest_tier;
1137   return task()->comp_level();
1138 }
1139 
1140 // ------------------------------------------------------------------
1141 // ciEnv::compile_id
1142 uint ciEnv::compile_id() {
1143   if (task() == NULL)  return 0;
1144   return task()->compile_id();
1145 }
1146 
1147 // ------------------------------------------------------------------
1148 // ciEnv::notice_inlined_method()
1149 void ciEnv::notice_inlined_method(ciMethod* method) {
1150   _num_inlined_bytecodes += method->code_size_for_inlining();
1151 }
1152 
1153 // ------------------------------------------------------------------
1154 // ciEnv::num_inlined_bytecodes()
1155 int ciEnv::num_inlined_bytecodes() const {
1156   return _num_inlined_bytecodes;
1157 }
1158 
1159 // ------------------------------------------------------------------
1160 // ciEnv::record_failure()
1161 void ciEnv::record_failure(const char* reason) {
1162   if (_failure_reason == NULL) {
1163     // Record the first failure reason.
1164     _failure_reason = reason;
1165   }
1166 }
1167 
1168 void ciEnv::report_failure(const char* reason) {
1169   EventCompilationFailure event;
1170   if (event.should_commit()) {
1171     CompilerEvent::CompilationFailureEvent::post(event, compile_id(), reason);
1172   }
1173 }
1174 
1175 // ------------------------------------------------------------------
1176 // ciEnv::record_method_not_compilable()
1177 void ciEnv::record_method_not_compilable(const char* reason, bool all_tiers) {
1178   int new_compilable =
1179     all_tiers ? MethodCompilable_never : MethodCompilable_not_at_tier ;
1180 
1181   // Only note transitions to a worse state
1182   if (new_compilable > _compilable) {
1183     if (log() != NULL) {
1184       if (all_tiers) {
1185         log()->elem("method_not_compilable");
1186       } else {
1187         log()->elem("method_not_compilable_at_tier level='%d'",
1188                     current()->task()->comp_level());
1189       }
1190     }
1191     _compilable = new_compilable;
1192 
1193     // Reset failure reason; this one is more important.
1194     _failure_reason = NULL;
1195     record_failure(reason);
1196   }
1197 }
1198 
1199 // ------------------------------------------------------------------
1200 // ciEnv::record_out_of_memory_failure()
1201 void ciEnv::record_out_of_memory_failure() {
1202   // If memory is low, we stop compiling methods.
1203   record_method_not_compilable("out of memory");
1204 }
1205 
1206 ciInstance* ciEnv::unloaded_ciinstance() {
1207   GUARDED_VM_ENTRY(return _factory->get_unloaded_object_constant();)
1208 }
1209 
1210 // ------------------------------------------------------------------
1211 // ciEnv::dump_replay_data*
1212 
1213 // Don't change thread state and acquire any locks.
1214 // Safe to call from VM error reporter.
1215 
1216 void ciEnv::dump_compile_data(outputStream* out) {
1217   CompileTask* task = this->task();
1218   if (task) {
1219     Method* method = task->method();
1220     int entry_bci = task->osr_bci();
1221     int comp_level = task->comp_level();
1222     out->print("compile %s %s %s %d %d",
1223                method->klass_name()->as_quoted_ascii(),
1224                method->name()->as_quoted_ascii(),
1225                method->signature()->as_quoted_ascii(),
1226                entry_bci, comp_level);
1227     if (compiler_data() != NULL) {
1228       if (is_c2_compile(comp_level)) {
1229 #ifdef COMPILER2
1230         // Dump C2 inlining data.
1231         ((Compile*)compiler_data())->dump_inline_data(out);
1232 #endif
1233       } else if (is_c1_compile(comp_level)) {
1234 #ifdef COMPILER1
1235         // Dump C1 inlining data.
1236         ((Compilation*)compiler_data())->dump_inline_data(out);
1237 #endif
1238       }
1239     }
1240     out->cr();
1241   }
1242 }
1243 
1244 void ciEnv::dump_replay_data_unsafe(outputStream* out) {
1245   ResourceMark rm;
1246 #if INCLUDE_JVMTI
1247   out->print_cr("JvmtiExport can_access_local_variables %d",     _jvmti_can_access_local_variables);
1248   out->print_cr("JvmtiExport can_hotswap_or_post_breakpoint %d", _jvmti_can_hotswap_or_post_breakpoint);
1249   out->print_cr("JvmtiExport can_post_on_exceptions %d",         _jvmti_can_post_on_exceptions);
1250 #endif // INCLUDE_JVMTI
1251 
1252   GrowableArray<ciMetadata*>* objects = _factory->get_ci_metadata();
1253   out->print_cr("# %d ciObject found", objects->length());
1254   for (int i = 0; i < objects->length(); i++) {
1255     objects->at(i)->dump_replay_data(out);
1256   }
1257   dump_compile_data(out);
1258   out->flush();
1259 }
1260 
1261 void ciEnv::dump_replay_data(outputStream* out) {
1262   GUARDED_VM_ENTRY(
1263     MutexLocker ml(Compile_lock);
1264     dump_replay_data_unsafe(out);
1265   )
1266 }
1267 
1268 void ciEnv::dump_replay_data(int compile_id) {
1269   static char buffer[O_BUFLEN];
1270   int ret = jio_snprintf(buffer, O_BUFLEN, "replay_pid%p_compid%d.log", os::current_process_id(), compile_id);
1271   if (ret > 0) {
1272     int fd = os::open(buffer, O_RDWR | O_CREAT | O_TRUNC, 0666);
1273     if (fd != -1) {
1274       FILE* replay_data_file = os::open(fd, "w");
1275       if (replay_data_file != NULL) {
1276         fileStream replay_data_stream(replay_data_file, /*need_close=*/true);
1277         dump_replay_data(&replay_data_stream);
1278         tty->print_cr("# Compiler replay data is saved as: %s", buffer);
1279       } else {
1280         tty->print_cr("# Can't open file to dump replay data.");
1281       }
1282     }
1283   }
1284 }
1285 
1286 void ciEnv::dump_inline_data(int compile_id) {
1287   static char buffer[O_BUFLEN];
1288   int ret = jio_snprintf(buffer, O_BUFLEN, "inline_pid%p_compid%d.log", os::current_process_id(), compile_id);
1289   if (ret > 0) {
1290     int fd = os::open(buffer, O_RDWR | O_CREAT | O_TRUNC, 0666);
1291     if (fd != -1) {
1292       FILE* inline_data_file = os::open(fd, "w");
1293       if (inline_data_file != NULL) {
1294         fileStream replay_data_stream(inline_data_file, /*need_close=*/true);
1295         GUARDED_VM_ENTRY(
1296           MutexLocker ml(Compile_lock);
1297           dump_compile_data(&replay_data_stream);
1298         )
1299         replay_data_stream.flush();
1300         tty->print("# Compiler inline data is saved as: ");
1301         tty->print_cr("%s", buffer);
1302       } else {
1303         tty->print_cr("# Can't open file to dump inline data.");
1304       }
1305     }
1306   }
1307 }