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